I have a simple ajax query to a file which basically returns in JSON error or success.
ie:
{"error":"1"}{"error_msg":" Invalid Expiry Date. Your credit card has not been billed for this transaction."}
The issue however is that even though I’m getting this json data return from my ajax post, I can’t seem to access the data at all.
My jquery looks something like this:
$.ajax({
type: 'POST',
url: 'process_sale.php',
data: $(this).serialize(),
cache: false,
dataType: 'json',
success: function(data) {
if(data['success']=='1'){
alert('hi');
$('#feedback').html('<strong>Congratulations</strong');
}
if(data['error']=='1') {
alert('hi');
$('#feedback').html(data['error_msg']);
}
// this following alert does nothing, because its empty even if the json
// returns what I pasted above example result.
alert(data['error'] + ' ' + data['success']);
}
});
None of the alerts will do anything.
Am I missing something really obvious here? I can’t seem to wrap my head around why this isn’t working as it seems to be fairly identical to other code I have working.
You’re trying to parse invalid JSON — you have two adjacent JSON objects in your example. You need to either place them in an array, or make them one object if you want JS to understand them:
Based on the rest of your code, I would wager that the first one will meet your needs better. You’re probably going to prefer to access the error message data[‘error’] and not data[0][‘error’]