Ingila Ejaz
Ingila Ejaz

Reputation: 233

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:

<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();
}


?>

Upvotes: 1

Views: 264

Answers (3)

Ingila Ejaz
Ingila Ejaz

Reputation: 233

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;
?>

Upvotes: 0

Rex Rex
Rex Rex

Reputation: 1030

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>

Upvotes: 1

Nandan Bhat
Nandan Bhat

Reputation: 1563

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.

Upvotes: 1

Related Questions