Andy
Andy

Reputation: 5395

What's wrong with this json response?

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

Answers (3)

Himanshu Upadhyay
Himanshu Upadhyay

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

puncoz
puncoz

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

akbansa
akbansa

Reputation: 393

From php file you need to encode it as

json_encode({"success":"success"});

And should expect dataType:'json'

Upvotes: 1

Related Questions