Ziplo
Ziplo

Reputation: 385

Use Jquery ajax json response?

:have an ajax request looking like this :

$.ajax({
          url: "/users/action/",
          type: "POST",
          data: myData,
          context: this,
          error: function () {},
          success : function () {
        $(this).removeClass('disabled');
          }
        });

So if the function is successfull, the class "disabled" is removed. However, my function returns the following json :

{"row":"fze684fz6f4ez68f4ze"}

I want to get this value so I can use it later "add it to a data element, i.e I want to add to the clicked element data-row="fze684fz6f4ez68f4ze"

How can I manage this ? I can't figure out by myself, I'm discovering AJAX.

Thanks a lot for your help !

Upvotes: 3

Views: 31166

Answers (3)

Dvir
Dvir

Reputation: 3339

It's recommend to set dataType if you excpect to get json . Any way pay attention to the context. It might be a problem with this.

$.ajax({
    url: "/users/action/",
    type: "POST",
    data: myData,
    context: this,
    error: function () {},
    dataType: 'json',
    success : function (response) {
        $(this).removeClass('disabled');
        $(this).data("row",response.row);
    }
});

Upvotes: 8

Adil
Adil

Reputation: 148150

You can use jQuery.data( element, key ) to assign row from returned response to element

$('selector').data('row', reseponse.row);

You can use id selector if you know the id of element

$('#elementId').data('row', response.row);

You can read more about selectors here.

Your code would be

$.ajax({
      url: "/users/action/",
      type: "POST",
      data: myData,
      context: this,
      error: function () {},
      success : function () {
           $(this).removeClass('disabled');
           $('#elementId').data('row', response.row);
     }
});

Upvotes: 2

SLaks
SLaks

Reputation: 887767

As the documentation clearly states, jQuery passes the server's response as the first parameter to the success callback:

      success : function (response) {
         console.log(response);
      }

Upvotes: 3

Related Questions