I’m trying to log the JSON data returned in the code below and it always returns as undefined in the console.
$.ajax({
url:"campcpcedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newcpc:newcpc},
success:function(data){
if (data.success) {
myAlertTop();
changeBid(_btn);
}
else {
myAlertBottom();
console.log(data.message);
}
}
});
The JSON response is this:
{"success":false,"message":"Error"}
The code to generate it in campcpcedit.php:
if($conn->query($upquery) === TRUE && $apiSuccess == "1") {
echo json_encode(array('success' => true));
}
else{
echo "Error: " . $upquery . "<br>" . $conn->error;
echo json_encode(array('success' => false,
'message' => "Error")
);
}
The if (data.success) is working as the 2 functions myAlertTop() and myAlertBottom() are firing properly.
I can’t find what I’m doing wrong.
2
Answers
The problem was that I have to parse the JSON response.
I’m surprised to hear that the solution was to use the following…
I believe the reason it is failing is because your PHP is returning the following example string back to the client, which the client can’t convert to an object (which the
$.ajax
will try and do by default).Instead, what I suggest is that you remove the first
echo
from your PHP, and instead add a new item to your array…That should result in a properly formed JSON string which can be parsed, meaning that the
data
variable insuccess:function(data)
is the object you’re expecting…