V.Srinath
V.Srinath

Reputation: 25

assign value to global variable in javascript

I want to assign value to global variable in javascript from jquery ajax function.

var trueFalse;
$.ajax({
   type: "GEt",
   url: "url",
   data: "text=" + $("#text").val(), 
   success: function(msg) {
     if(msg.match(/OK/) != null) {
       trueFalse = "true";
     }
     else {
       trueFalse = "false";         
     }
   }
});
return trueFalse;

here i need the value of trueFalse from success function.

thanks v.srinath

Upvotes: 0

Views: 2755

Answers (3)

roryf
roryf

Reputation: 30160

Your code won't work because the line return trueFalse; executes before the success function runs, since it is called as the result of an asynchronous (as in the A in Ajax) HTTP request. You would need to pass in a callback function to this code, and invoke that in the success function:

function getWithCallback(val, callback) {
    var scope = this;
    $.ajax({
        type: "GET",
        url: "url",
        data: "text=" + val,
        success: function(msg) {
            callback.call(scope, msg.match(/OK/) || false);
        }
    });
}

getWithCallback($("#text").val(), function(result) {
    if (result) {
        // Do something
    }
});

You could try this to validate a form on submit:

var validating = false;
var valid = false;

$('#myform').submit(function(event) {
    if (validating) {
        return false;
    }
    if (valid) {
        return true;
    }
    var form = this;
    validating = true;
    getWithCallback($('#text').val(), function(result) {
        if (result) {
            valid = true;
            form.submit();
        }
        validating = false;
    });
    return false;
});

You might also want to look at the jQuery Validation plugin

Upvotes: 4

einarq
einarq

Reputation: 535

Since you are doing this on form.onsubmit, you cannot do an async request. The browser won't know that it should wait until the async request is finished. The benefit of using async is that it does not lock up your scripts/browser, but in this case that is actually what you want.

Upvotes: 0

naivists
naivists

Reputation: 33511

If you really can't change the application logic, then you have to create a "synchronous" ajax request (by setting async:false in $.ajax options), then it will wait until the "GET" has executed and only then return the value to the caller.

Otherwise, you should rewrite the code so that the success function calls back into some callback function that it can now proceed with whatever has to be done.

Upvotes: 3

Related Questions