I have a javascript file that makes an AJAX call to a php file on the server which returns JSON encoded data. The PHP file can return either a success or a failure depending with about a dozen different messages like so:
if ( something here ) {
if( something else here ) {
if( more tests here ) {
$response['success'] = 'Successfully did something.';
} else {
$response['success'] = 'Successfully made this work';
}
} else {
$response['error'] = 'Failed to make the donuts.';
}
} else {
$response['error'] = 'I need more information!';
}
echo json_encode($response);
exit;
I have javascript/jquery on the front end that is checking for the response failure condition and displaying an alert box and performing some other relevent actions depending.
$.post(ajaxurl, data, function(response) {
if( response.hasOwnProperty("success") ) {
if( $(this).is( ":checked" ) ) {
$(this).removeAttr( "checked" );
} else {
$(this).attr( "checked", "true" );
}
alert( response["success"] );
} else {
alert( "Sorry, something went wrong. \nError: " + response["error"] );
}
});
The problem is that no matter how i check for the success condition it always displays the error message with a response['error'] of undefined I've tried testing for typeOf response['success'] != "undefined" and a number of other ways to see if the success value is set but nothing seems to work. I am getting a response that when I console.log it looks like so: { "success", "Successfully did something." } What am i doing wrong reading the message?