views:

248

answers:

3

Hello,

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

+3  A: 

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.

naivists
I tried async:false, but then too the page submits.
V.Srinath
I have not seen the code that calls this code, so I cannot comment. Are you calling this on form submit?
naivists
yes, i called the code from onsubmit. now everything works fine. thanks.
V.Srinath
+4  A: 

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

roryf
+1 for elegance. I think the first argument to the call method is the scope of `this`. `callback.call(null, msg||false)`
czarchaic
@czarchaic you're right, fixed so it uses the `this` scope from calling method (I think...)
roryf
A: 

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.

einarq