Reputation: 1100
I have a PHP script that outputs a JSON associative array when an ajax call is made to it. The first key and value in the array (["status" : "failed"]) shows the status. The second key and value (["message" : "Invalid Input"]) shows the message. So i need to first run a check whether the status is "failed", if it is, get the corresponding error message and vice versa.
The problem is how do I get the second key and value pair to get the message.
Here's the JavaScript I'm utilizing:
var frmdata = new FormData($('#order-form')[0]);
$.ajax({
type: "POST",
dataType: "json",
url: 'classes/validate.php',
cache: false,
contentType: false,
processData: false,
data: frmdata,
success: function(data) {
$.each( data, function( key, value ) {
if (key == "status") {
if (value == "failed") {
} else if (value == "success") {
}
}
});
}
});
Here's the PHP script;
public function outputJSON($status, $message)
{
$this->json_output["status"] = $status;
$this->json_output["message"] = $message;
$json = json_encode($this->json_output, true);
return $json;
}
Upvotes: 0
Views: 635
Reputation: 36609
Try this:
public function outputJSON($status, $message) {
$json = json_encode(array('status'=>$status,'message'=>$message));
return $json;
}
var frmdata = new FormData($('#order-form')[0]);
$.ajax({
type: "POST",
dataType: "json",
url: 'classes/validate.php',
cache: false,
contentType: false,
processData: false,
data: frmdata,
success: function(data) {
if (data.status === 'failed') {
alert(data.message);
} else {
//data.status is success
}
}
});
Upvotes: 1