views:

2181

answers:

5

What is the correct way of assigning to a variable the response from jQuery.get() ?

var data = jQuery.get("output.csv");

I was reading that jQuery.get() must have a callback function? why is that? and how would i use this callback function to assign the response back to the data variable?

Thanks in advance for your help and clarification.

Update:

Thank you all for your answers and explanations. I think i am starting to finally grasp what you are all saying. My code below is doing the right thing only the first iteration of it. The rest of the iterations its writing to the page undefined. Am i missing something?

<tbody>
<table id="myTable"> 

    <script type="text/javascript">

        $.get('output.csv', function(data) {
                csvFile = jQuery.csv()(data);

                for ( var x = 0; x < csvFile.length; x++ ) {
                    str = "<tr>";
                    for ( var y = 0; y < csvFile.length; y++) {
                        str += "<td>" + csvFile[y][y] + "</td>";
                    }
                    str += "</tr>";
             }
                $('#myTable').append(str);


        });

    </script>

</tbody>
</table>
+1  A: 

You just need to specify the callback function in the parameter to get method. Your data will be in the variable you specify in the function.

$.get("output.csv", function(data) {
    // Put your function code here, the 'data' variable will hold your data.
});
googletorp
+5  A: 

A callback function is required for asynchronous function calls, like an AJAX GET request. There is a delay between calling the get function and getting a response back, which could be a millisecond or several minutes, so you need to have a callback function that gets called when the asynchronous GET has completed its work.

Here's some more info on jQuery's AJAX get function: http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype.

From jQuery's examples:

// this would call the get function and just 
// move on, doing nothing with the results
$.get("test.php");

// this would return the results of the get
$.get("test.php", function(data){
  alert("Data Loaded: " + data);
});

If you get undefined when you try to use the data variable in the callback function, open up the console in Firebug in Firefox and watch the get request. You can see the raw request and the response that it comes back with. You should get a better indication of the issue after seeing what's being sent to the server and what's being sent back to the client.

Tim S. Van Haren
so, how do you workaround getting undefined?
I've updated my answer with a tip to help troubleshoot the data variable being undefined.
Tim S. Van Haren
@DCrawmer check what pixeline is saying. if the parse of the get request is taking too much is better to take the data in the callback. actually this is the correct way to do it.
Elzo Valugi
+1  A: 

Actually in your example the data will be the XMLHttpRequest request object.

var x;
$.get( 'output.csv', function(data){
    x = data;
    console.log(x); // will give you the contents.
});
Elzo Valugi
Given (to my understanding) that `get` is asynchronous, wouldn't the `log` be printing `undefined` every time?
Chris Jester-Young
yes, this code is giving me undefined every time, how do i prevent that?
put the console.log() call inside the callback!
pixeline
@pixeline is right. if the call takes too long the log is better in callback
Elzo Valugi
A: 
var manageCSV = function() {
    var x;

    $.get('output.csv', function(data) {
        x = data;
    });

    //do what you want with x
}

x as defined in an earlier answer will be undefined because it's out of scope.

You need to use a closure (as above) to contain the var x. which can be used outside of the get() method call.

The callback function is needed because the call to retrieve output.csv is asynchronous and will only be called when output.csv is retrieved.

HTH

Matt

Matt Goddard
after your code i added a loop that loops through this x array and i keep getting undefined.
x is still undefined here because the function to *fill* it is running (probably) well after the "// do what you want" section.Reading through the other comments, DCrawmer's obviously lost on the concept of "asynchronous" and event handlers.
clintp
+1  A: 

tsvanharen answered the question well, but DCrawmer's still missing the point. Let me attempt a clarification for him. I'm oversimplifying some of this, and smoothing over some details.

Look at the code shown below. This is pretty much the same code as tsvanharen's, except that I've replaced the anonymous function for the callback with an actual function pointer, and am a little more explicit so you can see what's going on:

var x = null;

function myCallback(data)
{
   alert("Data Loaded:" + data);
}

$.get("test.php", myCallback);

// the rest of your code
alert("The value of X is: " + x);

Assuming that test.php takes even a moment or two to load, notice the order that the alerts probably come up in:

1. "The value of X is"
2. "Data Loaded"

The function $.get() runs instantaneously. JavaScript moves on and runs the rest of your code right away. In the background, it's retrieving your page at test.php. jQuery hides some of the messy details of this.

The callback function (the second argument to $.get()) runs later (asynchronously). Or, said another way, the function myCallback is a handler to an event. That event is "$.get() has finished retrieving the data". It doesn't get run until that point. It doesn't run when $.get() runs! $.get() just remembers where that function is for later.

The function myCallback may run milliseconds or minutes later, long after $.get() has been dealt with.

If myCallback doesn't run until minutes later, then what's the value of x when the "The value of X" code is run? It's still null. There's your bug.

To use the data retrieved from the page in your script, you have to do things more like this:

  1. Start your script, declare your variable to hold the data.
  2. Call $.get(), with a callback function to handle the return.
  3. Do nothing else. [Or, at least, nothing that requires the data] Let the page just sit there.

    ...sometime in the future...

    X. Your callback function will get run, and have the results of your web page. Your callback function can: * Display the data * Assign that data to a variable * Call other functions * Go along it's merry way.

clintp
thank you very much for the clarification. please see my update to the question and tell me what am i doing wrong? thank you for your help.
Divide and conquer. Make sure that the jQuery.get is actually returning the data you think it is. Put an alert(data) at the beginning of the function to make sure that the data was read from output.csv correctly. (That's not a well-formed url, are you sure that's what you want?) Proceed from there.
clintp