4

I am trying to assign a value to the variable val in the code below:

var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;

function what(){
    val = update('#TAG#');
}


function update(tag) {
    var req1 = newXMLHttpRequest();
    req1.open("GET",cmdValue + tag, true);
    req1.send("");

    return req1.onreadystatechange= function () {
        if (req1.readyState == 4 && req1.status == 200) {
            returned_data = req1.responseText;
            return returned_data;
        }else{

        }
    };
}

I was tracking the variables in Firebug and it turns out that val gets assigned the function. Is there a way to get the code to run through and then assign the value to the variable val?

initramfs
  • 8,275
  • 2
  • 36
  • 58
Superios
  • 77
  • 1
  • 1
  • 9
  • 1
    http://stackoverflow.com/questions/6847697/how-to-return-value-from-callback-function – 0xcaff Oct 10 '13 at 14:10
  • as `val` is a global variable (which is not very recommended these days), you can do `var = returned_data;` – Zathrus Writer Oct 10 '13 at 14:12
  • I was keeping val as a global just so I could track it in firebug. DO you mean val=returned_data ? – Superios Oct 10 '13 at 14:13
  • yeah, sry I did mean `val = returned_data` – Zathrus Writer Oct 10 '13 at 14:21
  • Does the ajax request wait for a respose before it falls through the rest of the code. If it doesn't then what you are suggesting will not work. – Superios Oct 10 '13 at 14:24
  • @ZathrusWriter you can do what you suggested but in case the AJAX call takes longer than expected it will likely miss the assignment and disrupt execution if you have code that follows this assignment and depends on it. I know now that callbacks/handlers are the way to go. – Superios Oct 10 '13 at 18:31
  • Setting `val = returned_data` is pointless unless you know *when* that occurs - you need a callback function. – Adam Jenkins Oct 10 '13 at 18:31

2 Answers2

15

In asynchronous programming you do not return data because you don't know when that data is going to become available - it's asynchronous.

The way to do asynchronous programming is using events and/or callbacks.

Example:

var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;
var performSomeAction = function(returned_data) {
    val = returned_data;
}

function what(){
    update('#TAG#', performSomeAction);
}


function update(tag, callback) {
    var req1 = new XMLHttpRequest();
    req1.open("GET", cmdValue + tag, true);
    req1.send("");

    req1.onreadystatechange= function () {
        if (req1.readyState == 4 && req1.status == 200) {
            returned_data = req1.responseText;
            //fire your callback function
            callback.apply(this,[returned_data]);
        } else {

        }
    };
}

This question is one of the most commonly asked questions on SO, at least when it comes to the javascript tag - please search for similar questions before asking your own.

will.mendil
  • 752
  • 2
  • 6
  • 21
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • It's pretty difficult as a newbie to js because I never know the right keywords. Yes I already found a similar question. Thanks though. – Superios Oct 10 '13 at 18:50
  • What if I am working with synchronous code (last argument to open is false)? – Niko Jan 29 '18 at 07:28
  • @Niko You should never set the `async` argument to `false`. This will lock up the browser until the server responds. Always use proper asynchronous techniques instead. – Michael Geary Feb 03 '18 at 06:55
  • This might be a problem in typical browser applications where a user wants to see the content, but it might make sense in a different context. I guess you can pass your callback function to the "update" function and call that when the response is received. – Niko Feb 05 '18 at 08:39
  • 2
    @Niko - synchronous calls never ever make sense as the lock the browsers UI and feedback is unable to be provided to the user until the request is finished. Let's pretend their Wifi drops for a second - is my browser crashing? The interface isn't providing any feedback when I click on anything, nor is it even showing an (animated) loader - the entire UI is frozen? Do I need to CTRL+ALT+DELETE it? `Synchronous XMLHttpRequests = always bad`, full stop. – Adam Jenkins Feb 05 '18 at 12:22
-3
// should have a space after new or was did u notice it 
var req1 = new XMLHttpRequest();
Smern
  • 18,746
  • 21
  • 72
  • 90
Undercover
  • 23
  • 2