0

I'm trying to get the data returned from a page which is returning JSON to put itself into an array. This code works, however I can't put the variable (which should be the content) into the jQuery.parseJSON command. It works fine however when I use a ' ... ' string.

$.get( "server/php/index.php", function( data ) {
var data = jQuery.parseJSON(data);
});

If there is any other methods of doing this? What I'm trying to do is get the info from this page where it then puts itself into hidden input fields on a form.

Thanks in advance.

  • what is the value of `data`? is it a valid json – Arun P Johny Sep 18 '13 at 06:51
  • By the way there is a $.getJSON function in jQuery, so you woudn't need to use parseJSON I think – Victor Sep 18 '13 at 06:52
  • If I type console.log(data) in the browser I get: ReferenceError: data is not defined – Hayden McClure Sep 18 '13 at 06:53
  • What is the `typeof data`? Without an explicit [`dataType`](http://api.jquery.com/jQuery.get/), it's possible jQuery has already parsed the response as part of the "*Intelligent Guess*." – Jonathan Lonowski Sep 18 '13 at 06:53
  • So `data` is not defined, and yet you can't pass it to `parseJSON` ? – adeneo Sep 18 '13 at 06:54
  • 1
    Or, are you trying to reference `data` outside of the callback? If so, that's not going to work well. 1) `data` is only defined within that `function` being an argument and 2) `$.get()` is asynchronous and completes *after* surrounding code. For more on the latter, see "[How to return the response from an AJAX call?](http://stackoverflow.com/q/14220321)" – Jonathan Lonowski Sep 18 '13 at 07:01
  • 1
    can you post you json and some more code about how you are using data? – Moazzam Khan Sep 18 '13 at 07:05
  • Thanks guys, i've fixed the problem due to it being asynchronous. – Hayden McClure Sep 18 '13 at 07:16
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – John Dvorak Sep 18 '13 at 07:23
  • @HaydenMcClure would you post your solution and mark it as an answer? – Pavlo Sep 18 '13 at 07:51

2 Answers2

0

Don't pass the data into another variable called data. Call it something else and if you want to use it outside of your AJAX call then make sure you declare the variable elsewhere in your code so you can pass the data to it and use it.

var dataStorage;

$.get( "server/php/index.php", function( data ) {
    dataStorage = jQuery.parseJSON(data);
});
BenM
  • 4,218
  • 2
  • 31
  • 58
-1

Try removing the "var". Don't initialize data another time.

$.get( "server/php/index.php", function( data ) {
    data = jQuery.parseJSON(data);
});
Frax
  • 3,075
  • 1
  • 23
  • 27