Reputation: 5395
I've copied the accepted answer to a question How do I return a proper success/error message for JQuery .ajax() using PHP?
My PHP script is returning the following json. The headers are correct: Content-type: application/json
and json_encode()
on the output in the PHP script:
{"success":"success"}
But the jquery to check the status isn't working:
$.ajax({
type: "POST",
url: '/ajax/index',
data: $("#NewsletterSignup").serialize(),
success: function(data)
{
console.log(data);
if (data.success == 'success') {
console.log('successful');
} else if(data.errors){
console.log('error occurred');
}
}
});
So I get the initial console.log(data)
which gives {"success":"success"}
. But then it's not evaluating the if...else if
condition. Why?
jquery version is 1.12.3
Upvotes: 0
Views: 71
Reputation: 6565
Add dataType to your ajax code like this:
$.ajax({
type: "POST",
url: '/ajax/index',
data: $("#NewsletterSignup").serialize(),
dataType:'json,' // CHECK THIS....
success: function(data)
{
console.log(data);
if (data.success == 'success') {
console.log('successful');
} else if(data.errors){
console.log('error occurred');
}
}
});
Upvotes: 1
Reputation: 496
That is because your php server gives response as a plain text not json. Look at the header Content-Type: text/html
. Your server need to send header as a json with Content-type: application/json
.
<?php
$data = /** whatever you're serializing in array **/;
header('Content-Type: application/json');
echo json_encode($data);
Alternatively, if response is in plain text
, you can parse that response to json in client side (javascript). Do this:
$.ajax({
type: "POST",
url: '/ajax/index',
data: $("#NewsletterSignup").serialize(),
success: function(data)
{
data = JSON.parse(data);
console.log(data);
if (data.success == 'success') {
console.log('successful');
} else if(data.errors){
console.log('error occurred');
}
}
});
Also you can expect json response in in jquery ajax, by using dataType:'json'
option.
Upvotes: 0
Reputation: 393
From php file you need to encode it as
json_encode({"success":"success"});
And should expect dataType:'json'
Upvotes: 1