5

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.
        }
    });
};
3
  • Few questions: - From where will you call your Save Function? - How are you passing the reference of 'p' to Save function? Commented Apr 4, 2012 at 12:12
  • p in your second example is not a global object, thus you would need to set something else if you wish to retain that ID value somehow. Commented Apr 4, 2012 at 12:30
  • Did you even try your code? Your code should actually work. Keep in mind there are some issues with then being asynchronous like pointed by trickyzter. Try add to your ajax calls async: false to see it working. Commented Apr 4, 2012 at 12:56

3 Answers 3

1

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;
});
Sign up to request clarification or add additional context in comments.

Comments

0

There may be better ways to do this but I'd have my database also return the Name and Surname along with the ID, then search my Person list to find the correct object in the success function.

Comments

0

Perhaps this is what you desire?

I borrowed some code here:

/*** makeClass() ***
 * The following allows us to easily create
 * Javascript classes.  Source of this:
 * http://ejohn.org/blog/simple-class-instantiation/
 * makeClass - By John Resig (MIT Licensed)
 */

function makeClass() {
    return function(args) {
        if (this instanceof arguments.callee) {
            if (typeof this.init == "function") this.init.apply(this, args.callee ? args : arguments);
        } else return new arguments.callee(arguments);
    };
});

/* set up ajax */
$.ajaxSetup({
    async: false,
    type: "POST",
    contentType: "application/json",
    converters: {
        "json jsond": function(msg) {
            return msg.hasOwnProperty('d') ? msg.d : msg;
        }
    },
    data: '{}',
    dataType: "json",
    error: function(jqXHR, status, error) {
        alert("An error occurred on the server. Please contact support.");
    }
});

/* set up my person class */
var personClass = makeClass();
personClass.prototype.init = function() {
    this.ID = '';
    this.SurName = '';
    this.Name = '';
}

/* create my save function */
personClass.prototype.SavePerson = function(p) {
    this.Name = (typeof p === 'undefined') ? this.Name : p.Name;
    this.SurName = (typeof p === 'undefined') ? this.SurName : p.SurName;
    $.ajax({
        url: "Save",
        data: JSON.stringify({
            Name: this.Name,
            SurnName: this.SurName
        }),
        success: function(result) {
            var ID = result.ID; //ID  from database
            this.ID = ID; //set the ID, 
        }
    });
};
//create two persons
var person1 = personClass();
var person2 = personClass();

//set person1 to be fred
person1.Name = "Fred";
person1.SurName = "Flintstone";

// independent person
var p = {Name: "Barney", SurName: ""};
p.Surname = "Rubble";

//save specific and the independent (as person2)
person1.SavePerson();
person2.SavePerson(p);

//alert the ID of both
alert(person1.ID + ":" + person2.ID);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.