Robert Ross Robert Ross - 14 days ago 5
jQuery Question

Ajax request to php failing?

I am trying to do an ajax request to my php, but for some unknown reason it seems to fail as i don't get to the success part where I have a

console.log


Can anyone please give me some hint what might be wron with this, I am stuck for too long now??

Here is how my jQuery looks :

getPending();
function getPending(){
var usernameLS = localStorage.getItem('userNameLS');
var userTypeLS = localStorage.getItem('isAdminLS');

if (userTypeLS!=1) {
console.log("inside");//i am getting here
$.ajax({
type: "POST",
dataType: 'json',
url: 'get-pending.php',
data: {
data: usernameLS //this is a string, "user2" for instance
},
success: function(data) {
console.log("Thanks!!!",data);//i never got here

},
failure: function() {
console.log("Error!");
alert(' Fail');
}
});
}


And here is my php :

<?php
$string = file_get_contents("appointments.json");
$usernameAjax = $_POST['data'];
var_dump($usernameAjax);
$json_a = json_decode($string, true);
$isPending;
foreach ($json_a as &$json_r) {
if ($usernameAjax==$json_r['userName'] && $json_r['status'] = "Pending") {

$isPending = 1;
}
else{
$isPending = 0;
}
}
var_dump($isPending);
echo $isPending; //i tried with a hardcodede 1 or 0 zero. Didn't work.
?>

Answer

Seems like your output is not correct JSON format, so client-side cant understand what was recieved.

First - remove var_dump, it breaks json format anyway;

Second - jou just output 1 or 0 - that is not correct json too; use json_encode to format reply properly;

Third - php files often contains trailing symbols after ?>, that are appends to output too and could break output format. Dont close php with ?> at all; additionally you could use die($output) instead of echo($output) to avoid any output after your data was written

Comments