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.
}
});
};
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With