-1

I am using jQuery to pull in data from a csv. The request is successful (Success!! in the console) and I can see the data in the responseText field when I print the object but I can't print data.responseText (shows in console as "undefined").

window.onload = function(){

    console.log("start");
    var data = $.ajax({url:"http://localhost/bootstrap/data/930.csv",success:function(){
        console.log("Success!!");
        }()
    });
    console.log(data);
    console.log(data.responseText);

How do I access responseText to transform it?

EDIT:

Updated my code per comments to force sync and modified the variables to better follow them. Still I was surprised by the result.

console.log("start");
    var ajaxData = $.ajax({url:"http://localhost/bootstrap/data/930.csv",async:false,success:function(dataReturned){
        console.log("Success!!"); //Success!!
        console.log(dataReturned); //Returns my csv data
        console.log(dataReturned.responseText); //undefined
        }
    });
    console.log(ajaxData); //Returns a jQuery object that included my csv data
    console.log(ajaxData.status); // Returns 200
    console.log(ajaxData.responseText); //Returns my data (same as dataReturned in success function)

So I guess I also missed that the jQuery object isn't created and available until the complete $.ajax call finishes but the response is available sooner.

Thanks for the help.

moto_beats
  • 39
  • 9
  • 1
    Welcome to the world of Asynchronous Programming. Use the call back – epascarello Aug 29 '14 at 20:22
  • See also [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – Felix Kling Aug 29 '14 at 20:30

1 Answers1

0

Please learn about asynchronous methods. You need to use the callback. What you tried to do is eat a delivery pizza right after you hung up the phone. You need to wait until the guy delivers it.

$.ajax({url:"http://localhost/bootstrap/data/930.csv",success:function(data, status, xhr){
    console.log("Success!!");
    console.log(data);
    console.log(xhr.responseText);
    }
});
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Ok, I missed the async thing. However the logging from the code above surprises me. (data) is the response I am looking for (I was expecting the object to be returned. (data.responseText) is still undefined. – moto_beats Aug 29 '14 at 20:50