Ajax returning blank response

I’m working on a simple script where I just want to see request and response that is sent to server and then recieved at client via Ajax. The server is always returning Status 500. What am I doing wrong?
Below is my script.

Javascript:

Read More
<script>
function loginJs()
{

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET","http://my-website.com/ajax_exp.php",true);

xmlhttp.onreadystatechange=function()
{  

 alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
    alert(xmlhttp.responseText);
 }
}
xmlhttp.send();
}
</script>

ajax_exp.php

<?php

header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
add_action('wp_ajax_my_action',        'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');

function my_action()
{
$username = 'username';
$password = 'password';

echo $username;
die();
}


?>

Related posts

Leave a Reply

3 comments

  1. 1) try removing

     header('Access-Control-Allow-Origin: http://my-website.com/ajax_exp.php');
     add_action('wp_ajax_my_action',        'my_action');
     add_action('wp_ajax_nopriv_my_action', 'my_action');
    

    replacing with

     my_action();
    

    You can easily trace the error;

    2) Check console log for any javascript errors.

  2. Path is the problem provide your server path ajax/ajax_exp.php

    <script>
    function loginJs()
    {
    
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.open("GET","ajax/ajax_exp.php",true);
    
    xmlhttp.onreadystatechange=function()
    {  
    
     alert("State "+xmlhttp.readyState+" Status "+xmlhttp.status);
     if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
        alert(xmlhttp.responseText);
     }
    }
    xmlhttp.send();
    }
    </script>
    
  3. If anyone else is having the same issue, this is what I did and now it works!

    Javascript

    Replaced xmlhttp.send(); with xmlhttp.send(null);

    PHP

    <?php
    $username = "user";
    $password = "password";
    print $username;
    ?>