Jquery ajax success function not executed?
json
Here is the json output from /controll/operation.php?p=demo
{"message-count":"1","messages":[{"to":"3321313","status":"6","error-text":"Unroutable message - rejected","network":"MV-FIXED"}]}
This is a valid json checked from jason validator.
javascript code
$('#send').click(function()
{
var to = $('#to').val();
var sender = $('#sender').val();
var message = $('#message').val();
if (to == "") {
$("#forto").addClass("has-error");
return false;
}
if (sender == "") {
$("#forsender").addClass("has-error");
return false;
}
if (message == "") {
$("#formessage").addClass("has-error");
return false;
}
$("#send").prop( "disabled", true );
$("#alert").html('<img style="display:block;margin:0 auto 0 auto;" src="../images/loading.gif">');
$.ajax("../controll/operation.php?p=demo", {
type: "POST",
async: true,
dataType: "json",
data: { "to": to, "sender": sender, "message": message},
success: function (response) {
var table = '<div align="center">';
for (var i = 0; i < response.messages.length; i++)
{
var status = response.messages[i].status;
var to = response.messages[i].to;
var messageprice = response.messages[i].messageprice;
var remainingbalance = response.messages[i].remainingbalance;
var errortext = response.messages[i].errortext;
if(status == "0")
{
status = "Message sent successfully to ";
}
else
{
status = errortext;
}
table = table + '<p>'+status+to+'</p>';
}
table = table + '</div>';
$("#alert").html(table);
$("#send").prop( "disabled", false);
},
error: function (header, status, error) {
console.log('ERROR' + header + ' ' + status + ' ' + error);
}
});
});
browser console output
ERROR[object Object] parsererror SyntaxError: Unexpected end of input
You need to parse the response text as JSON object. See the below example.
var jsonData = '{"message-count":"1","messages":[{"to":"3321313","status":"6","error-text":"Unroutable message - rejected","network":"MV-FIXED"}]}';
var data = $.parseJSON(jsonData);
$.each(data.messages, function(i, item) {
alert(item.to);
alert(item.status);
});
However, error-text
is not getting accessed as it contain a special character in it. so better to rename it from server side as errortext
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.