Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving javascript objects using jquery and passing an ID from database

I am using jQuery to save the values of my javascript objects. I need to retreive the ID of inserted object from the database. I know how to do it, if the Save function is within the javascript object (see code below). But how can I set the ID variable, if the Save function is not in the javascript object?

Working:

Person = function() {
    var self = this;

    self.ID;
    self.Name;
    self.SurName;

    self.Save = function() {
        $.ajax({
            type: "POST",
            url: "Save",
            contentType: "application/json; charset=utf-8", 
            data: JSON.stringify({ Name: self.Name, SurnName: self.SurName }),
            dataType: "json",
            success: function (result) {
                var ID = result.d.ID; //this is the ID retreived from database
                self.ID = ID; //set the ID, it works, since I can reference to self
            }
        });
    };
}¨

So how would I now implement a function (outside the Person class!) like:

SavePerson = function(p) {
     $.ajax({
        type: "POST",
        url: "Save",
        contentType: "application/json; charset=utf-8", 
        data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
        dataType: "json",
        success: function (result) {
            var ID = result.d.ID; //this is the ID retreived from database
            p.ID = ID; //set the ID, it doesn't work, becouse if I call SavePerson repetedly for different objects, a p will not be a correct person.
        }
    });
};
like image 491
Matej Avatar asked Nov 13 '22 07:11

Matej


1 Answers

Just to clarify, you would like the Person object id property to be updated with the recent save? If so the following script would suffice. I have used deferred's to ensure that p.ID is only updated upon completion of the asynchronous request.

$.Person = function() {
    var self = this;
    self.ID;
    self.Name;
    self.SurName;
}

$.SavePerson = function() {
var dfd = $.Deferred();
     $.ajax({
        type: "POST",
        url: "Save",
        contentType: "application/json; charset=utf-8", 
        data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
        dataType: "json",
        success: dfd.resolve
    });
return dfd.promise();
};

var p = new $.Person();

$.SavePerson().then(function(result){
    p.ID = result.d.ID;
});
like image 123
trickyzter Avatar answered Nov 16 '22 03:11

trickyzter