来自PHP结果的jQuery json

I have this jQuery script

var dataString = "class_id="+class_id;

$.ajax({
    type: "POST",
    url: "page.php",
    data: dataString,
    success: function (msg) {
        //stuck here
    },
    error: function () {
        showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
    }
});

my PHP output is something like this

echo '{status:1,message:"Success"}';

or

echo '{status:0,message:"Failure"}';

what I am trying to do in jQuery success: function(...) part is check if status is 0 or 1 and then show the message.

I tried to do is

success: function(text) {
   if(parseInt(text.status) == 1) {
      alert(text.message); // this is the success, the status is 1
   } else {
      alert(text.message); // this is the failure since the status is not 1
   }
}

which didn't work, it was only outputing the else statement, even though the status was 1

Try something like below,

$.ajax({
    type: "POST",
    url: "page.php",
    data: dataString,
    dataType: 'json',
    success: function (msg) {
        if (msg.status == 0) {
          alert("Success " + msg.message);
        } else if (msg.status == 1) {
          alert("Error " + msg.message);
        }
    },
    error: function () {
        showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
    }
});

Your PHP is generating invalid JSON, and shows no sign of setting an appropriate content type header to tell the browser to treat it as JSON in the first place. So first, fix the PHP:

header('application/json');
echo json_encode(Array("status" => 1, "message" => "Success"));

Then:

success: function (msg) {
    alert(msg.message)
},

You can also use

PHP

echo json_encode(Array("status" => 1, "message" => "Success"));

JS

Inside your call back function use

success: function (msg) {
    $.parseJSON(msg);
    alert(msg.message);
}

The parseJSON will convert the json string returned/echoed by PHP in to json object.

If you don't specify in $.ajax the type 'json' data passed to response handler is treated as string. While if you specify 'json' dataType parameter you can use:

msg.status 

and

msg.message

As a hint i suggest in php to use the json_encode function to generate json output.