---
title: "jquery-ujs and jquery trigger"
description:
  "This blog discusses how to make AJAX calls using jquery-ujs. Also discusses
  why event object is needed which is often the cause of error with lot of code."
canonical_url: "https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger"
markdown_url: "https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger.md"
---

# jquery-ujs and jquery trigger

This blog discusses how to make AJAX calls using jquery-ujs. Also discusses why
event object is needed which is often the cause of error with lot of code.

- Author: Neeraj Singh
- Published: May 11, 2012
- Categories: jQuery

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](http://api.jquery.com/jQuery.ajax/) .

```javascript
success(data, textStatus, jqXHR);
```

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

```javascript
$.ajax({
  url: "ajax/test.html",
  success: function (data, textStatus, jqXHR) {
    console.log(data);
  },
});
```

## ajax using jquery-ujs

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

```plaintext
<a href="/users/1" data-remote="true" data-type="json">Show</a>
```

```javascript
$("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.

```javascript
$("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.

## Why event object is needed

Here is snippet from jquery-ujs code

```plaintext
success: function(data, status, xhr) {
  element.trigger('ajax:success', [data, status, xhr]);
}
```

The thing about [trigger](http://api.jquery.com/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.

## Links

- [Human page](https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger)
