kingrichard2005
kingrichard2005

Reputation: 7289

jQuery to load text file data

I'm trying to load data from a text file on my server using the $.get() function in an external script file. My code is as follows:

  /* 
   * Load sample date
   */
  var stringData;
  $.get("http://localhost/webpath/graphing/sample_data.txt", function(data){
      stringData = data;
      //alert("Data Loaded: " + stringData);
      });
  //Split values of string data
  var stringArray = stringData.split(",");
  alert("Data Loaded: " + stringData);

When I'm inside the $.get() function I can see stringData var get peopulated just fine and the call to alert confirms that it contains data from the sample text file. However, when I get outside the $.get() function, the stringData var no longer shows. I don't know enough about how the function works to know why it is not doing as I expected. All I want it to do is load the text data into a variable so I can work with it. Any help is appreciated.

Upvotes: 3

Views: 21212

Answers (2)

Praveen Lobo
Praveen Lobo

Reputation: 7187

get is asynchronous meaning it makes a call to the server and continues executing the rest of the code. This is why you have callback methods. Whatever you intend to do with the return data do it inside the callback method(where you have put the alert).

get, post are all asynchronous. You can make a synchronous call by using

  1. using $.ajaxSetup({ async: false }); anywhere in your code. This will affect all ajax calls in your code, so be careful.

  2. $.ajax with async: false e.g. shown below.

Look at the below code and the API docs link mentioned above to fix your problem.

  /* 
   * Load sample date
   */
  var stringData = $.ajax({
                    url: "http://localhost/webpath/graphing/sample_data.txt",
                    async: false
                 }).responseText;

  //Split values of string data
  var stringArray = stringData.split(",");
  alert("Data Loaded: " + stringData);

Upvotes: 18

joekarl
joekarl

Reputation: 2118

The $.get function is asynchronous. You'll need to do any work on the returned data in the callback function. You can move that function to not be inline to clean up the code as well.

    function parseData(data){
        //do something with the data
        alert("data is: " + data);
    }

    $.get("http://localhost/webpath/graphing/sample_data.txt",parseData);

Upvotes: 5

Related Questions