jquery-ujs and jquery trigger

Neeraj Singh

Neeraj Singh

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 .

1success(data, textStatus, jqXHR);

So if you are making ajax call using jQuery the code might look like

1$.ajax({
2  url: "ajax/test.html",
3  success: function (data, textStatus, jqXHR) {
4    console.log(data);
5  },
6});

ajax using jquery-ujs

If you are using Rails and jquery-ujs then you might have code like this

1<a href="/users/1" data-remote="true" data-type="json">Show</a>
1$("a").bind("ajax:success", function (data, status, xhr) {
2  alert(data.name);
3});

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.

1$("a").bind("ajax:success", function (event, data, status, xhr) {
2  alert(data.name);
3});

Remember that jQuery api says that the first parameter should be "data" then why we need to pass event object to make it work.

Why event object is needed

Here is snippet from jquery-ujs code

1success: function(data, status, xhr) {
2  element.trigger('ajax:success', [data, status, xhr]);
3}

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.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.