Sunday, 20 November 2016

jquery ajax call question



In a jQuery ajax statement I want to receive a payload from the server and process it in another function. I am just having trouble with the syntax of the function.




$.ajax({

url: 'mypgm.pgm',
type:'POST',
dataType: 'json',
data: 'action=add' +
'&techno=' + techno +
'&activity=' + activity,
success: ajax_callback(msg),
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);

}
});
}

function ajax_callback(msg) {

alert(msg);
}



Response




{"response": {
"success": "0",
"message": "The Activity has been added."
}
}

Answer




A success callback handler for $.ajax() can take in the following values:



success(data, textStatus, jqXHR)


Source: http://api.jquery.com/jQuery.ajax/



So your function callback would be something like this:



function ajax_callback(data, textStatus, jqXHR)     

{
alert(data.response)
}


Note how I created a named function this way, instead of assigning it to a var. If you only care about the data, you can just leave the last 2 parameters off:



function ajax_callback(data)     
{
alert(data.response)

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...