1

Can any one help me what im wrong in

function separateerror()
{
    var jqxhr = $.get("/errormsg.txt", function(data) {
        line = data;
        array = line.split(',');
        getmsg=array[0];
    })
    return getmsg;
}

i need to return "getmsg" to another function, but its not working, where as if i add alert inbetween

function separateerror()
{
    var jqxhr = $.get("/errormsg.txt", function(data) {
        line = data;
        array = line.split(',');
        getmsg=array[0];
    })
    //alert(getmsg)
    return getmsg;
}

the value returns, what wrong im doing in code?

1
  • how/where are you calling this function separateerror?? Commented Oct 4, 2011 at 12:58

2 Answers 2

3

$.get is an async call and what happens is that if you add an alert in between, you give time for the async call to finish and then your value is already set by the time the separateerror function finishes. Otherwise, the separateerror function returns before the $.get call finishes and then your getmsg is probably still a null value.

While working with async calls you should not use this simple model of calling functions and expecting theirs values in return, you should use callback functions to accomplish that the right way.

EDIT: Also, you should handle the $.get error callback, in case something happens and you can not load the txt file.

function separateerror()
 {
    var jqxhr = $.get("/errormsg.txt", function(data) {
       line = data;
       array = line.split(',');
       getmsg=array[0];
       dosomething(getmsg);
    })
    .error(function() { alert("error"); });
}

function dosomething(msg) { ... }
Sign up to request clarification or add additional context in comments.

Comments

1

Insert that to the top of your script. That /should/ fix it.

$.ajaxSetup({
  async: false
});

3 Comments

What if he needs more ajax calls - it would be better if they were asynchronous.
This will work, but it is not a fix as the asynchronous behavior is the one expected. This is a good hack if you do not need any asynchronous calls whatsoever now and in the future. If you ever need to perform a async calls in the future, get ready for some headaches
True. Guess that's why you have more rep than I do. I never thought about what would happen after this was invoked. I just thought about a quick fix to a problem. I have much to learn, thanks, guys.

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.