May 11, 2012
Let's see how to make AJAX call using jquery.
jQuery's ajax method's success
callback function takes three parameters. Here
is the api .
success(data, textStatus, jqXHR);
So if you are making ajax call using jQuery the code might look like
$.ajax({
url: "ajax/test.html",
success: function (data, textStatus, jqXHR) {
console.log(data);
},
});
If you are using Rails and jquery-ujs then you might have code like this
<a href="/users/1" data-remote="true" data-type="json">Show</a>
$("a").bind("ajax:success", function (data, status, xhr) {
alert(data.name);
});
Above code will not work. In order to make it work the very first element passed to the callback must be an event object. Here is the code that will work.
$("a").bind("ajax:success", function (event, data, status, xhr) {
alert(data.name);
});
Remember that jQuery api says that the first parameter should be "data" then why we need to pass event object to make it work.
Here is snippet from jquery-ujs code
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
}
The thing about trigger method is that the event object is always passed as the first parameter to the event handler. This is why when you are using jquery-ujs you have to have the first parameter in the callback function an event object.
If this blog was helpful, check out our full blog archive.