Alex
Alex

Reputation: 65

Can I use jquery's .done() more than once?

I have 2 JS literals:

var obj1 = {
    Add: function (id) {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                "id": id
            }),
            url: "Page.aspx/add",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                return jQuery.parseJSON(data.d || "null");
            }
        });
    }
};
var obj2 = {
    List: function (id) {
        $.ajax({
            type: "POST",
            data: JSON.stringify({
                "id": id
            }),
            url: "Page.aspx/list",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                return jQuery.parseJSON(data.d || "null");
            }
        });
    }
};

And this is my document.ready:

$(document).ready(function () {
    obj1.Add(1).done(function (data) {
        alert('you added ' + data);
    });

    obj2.List().done(function (data) {
         $.each(jQuery.parseJSON(data), function (i, item) {
            // fill a combo box
        });
    });
});

jQuery just executes the first call and obj2.List() ain't called at all. How to properly use the deffered objects in this case?

Upvotes: 2

Views: 108

Answers (1)

Royi Namir
Royi Namir

Reputation: 148704

Change your Add and List function to RETURN the ajax object.

 Add: function (id) {
                 return  $.ajax({..

and

 List: function (id) {
         return   $.ajax({...

This way - it will return the jqXHR obj which will return the deferred object. This implement the Promise interface which has : the callbacks you are looking for.

edit :

look at this simple example which does work :

var obj1 = {
    Add: function (id) {
      return  $.ajax({
            type: "get",
            data: JSON.stringify({
                "id": 1
            }),
            url: "http://jsbin.com/AxisAmi/1/quiet",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
              
              
              alert("at success --"+data.data)
            }
        });
    }
};

obj1.Add(2).done(function (a){alert("at done --"+a.data);});

enter image description here

enter image description here

Upvotes: 2

Related Questions