0

I have been working on this for the past 2 hours. I am getting the error, SyntaxError: Unexpected token u when I try to parse a GET request using a function. But I perform the same code one line at a time it works fine.

I noticed that as soon as I create an object its readyState is 1, but right after I save it and wait a second the readyState changes to 4 then it parses fine.

I thought that maybe the XmlHttpObject I am pulling just needs to communicate to the server after the object is already on my computer, like maybe it is not done pulling all information and once the information pull is complete it turns it to 4. As a result of this realization I tried to use the timeout function to wait a few seconds then try to parse it, but I still couldn't get it to work!

Here is my code:

 function pullData(){
  var obj = $.get("https://api.parse.com/1/classes/chats");
  var object_array = JSON.parse(obj.responseText);
      return object_array
    }
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100

2 Answers2

1
function pullData(callbackFunction)    
  $.get( "https://api.parse.com/1/classes/chats", function( data ) {
    var object_array = JSON.parse(data);
    callbackFunction(object_array);
  });
}

JavaScript ajax calls are asynchronous, so u can't get the result at next line code after you perform get request, because get request is executed in background.

JQuery has a great documentation to look how to write ajax requests. http://api.jquery.com/jquery.get/

StrekoZ
  • 618
  • 6
  • 12
  • Ahh, that makes a lot more sense. But I am getting "Uncaught SyntaxError: Unexpected identifier" on the second line of code in your example, " $.get( "https://api.parse.com/1/classes/chats", function( data )" – chopper draw lion4 Jun 29 '14 at 17:22
  • It's just a copy-paste error. there should be line like: var object_array = JSON.parse(data); – StrekoZ Jun 29 '14 at 17:24
  • 1
    This still might throw a Syntax Error if jQuery parses the JSON for you (which is likely), and your callback passes to parsed object to `JSON.parse`. Better use `$.getJSON`. – Bergi Jun 29 '14 at 17:29
-1

Why don't you try

function pullData(){
   $.get("YOUR_URL")
   .done(function(data) {
      var object_array = JSON.parse(data); 
      return object_array
  })
}
Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84