Himanshu
Himanshu

Reputation: 41

javascript updating hidden value

I have a function:

function add() {
    $.ajax({
        type: "POST",
        url: "add.php",
        async: "false", // Tried both- async: "false/true"
        data: {
            name: 'Test',
        },
        success: function(data) {
            document.getElementById('id').value = data;
            id = document.getElementById('id').value;
            alert(id); // alerts here proper value
        }
    });

}

function testMyFunction() {
    add();

    // 'id' was set in add function.
    id = document.getElementById('id').value;
    alert(id); // Here does not alert value but blank(no value)
    // This 'id' value is used at other place but here is issue. 
}

Calling testMyFunction() function gives above mentioned issue.

What could be a issue?

Upvotes: 0

Views: 66

Answers (2)

Andrew Dunai
Andrew Dunai

Reputation: 3129

JavaScript is an asynchronous language. In a nutshell, this means that your code should NEVER block: functions should either complete immediately or get called later, i.e. after some input/output operation is complete (e.g. AJAX request).

Edited: BTW, your code does not work because even with async: false the success function is called in the event loop, thus this can occur even after the code that follows synchronous AJAX. If you use async: true, the AJAX will block, but the success function will be called asynchronously in any case. So to handle data synchronously, you have to work not with success function, but rather with an object that is returned by $.ajax() call:

var xhr = $.ajax({
    type: "POST",
    async: false,
    url: "add.php",
    data: {
        name: 'Test',
    },
});
alert(xhr.responseText); // Alerts result

Thus, you should never use async: false. Instead, better refactor your code to be like this:

function add(callback) {
    $.ajax({
        type: "POST",
        url: "add.php",
        data: {
            name: 'Test',
        },
        success: callback
    });
}

function testMyFunction() {
    add(function(data) {
        // This closure will be called AFTER the request is complete.
        document.getElementById('id').value = data;
        alert(data); // Alerts proper value.
    });
}

Basically, this pseudo-code is WRONG:

result1 = action1();
result2 = action2(result1);
result3 = action3(result2);

...and should be written like this:

action1(function(result1) {
    action2(result1, function(result2) {
        alert(action3(result2));
    });
});

Upvotes: 3

Michal Wilkowski
Michal Wilkowski

Reputation: 747

$.ajax is an asynchronous call and it updates "id" field after if it is completed. Your code checks for its value in function testMyFunction() instantly after the invocation (and before success: function(data) is invoked).

Upvotes: 3

Related Questions