user4359719
user4359719

Reputation:

Can't retrieve an id previously passed in jQuery

I have this code actually:

$("#myForm").submit(function(event) {
    event.preventDefault();
    $.when(getDatas(this.id)).done(function(r_getDatas){
        var json = $.parseJSON(r_getDatas);
        alert(this.id);
    });

    function getDatas(id) {
        return $.post("update.php", {
            updateType: id,
            data: $('#'+id).serializeArray()
        }, "json");
    }           
});

How can I run this line is the code:

alert(this.id);

Actually, the alert says:

undefined

Thanks.

Upvotes: 0

Views: 47

Answers (1)

PolGraphic
PolGraphic

Reputation: 3364

Are you sure that this.id has an right value (different then undefined) in line $.when(getDatas(this.id))?


If so, try something like this:

$("#myForm").submit(function(event) {
event.preventDefault();
var myID = this.id;
$.when(getDatas(myID)).done(function(r_getDatas){
    var json = $.parseJSON(r_getDatas);
    alert(myID);
});

That way you capture and store the value of this.id into variable. When you use alert(this.id) your this may have a different scope (meaning) then previously and the variable will keep the right value.


On Firefox you can examine the value of variable in any given place of code with: console.log(variable), e.g.:

console.log("My ID = " + myID);

I suggest you to check the value of this.id before calling $when(getDatas(...)) and inside the function getDatas(...){...}.

Upvotes: 2

Related Questions