-1

I have been searching the web like crazy for a day straight trying to figure out why my javascript code is not working. I am trying to pass an array from PHP to Javascript using JSON. After that i want to use it in other functions, thus kinda making the array or variable global. But i have been unable to get it to work, here is my code so far:

data = [];
$(document).ready(function() {
  $.getJSON('database.php', function(phpdata){
    // vad du vill göra här, allt retuneras i data-variabeln
    console.log(phpdata);
    data[0] = phpdata[0];
    console.log(data[0]);
  });

console.log(data);

Any ideas?

Bobbie
  • 9
  • 2

2 Answers2

1

When $.getJSON is called, the JS engine will step parallely to the next instruction, which here is console.log(data);. This behaivour is caused to $.getJson's asynchronuality.

Since the next step is calculated and executed in the very next millisecond, the webpage was not fully requested and data is still on its initialized value ([]).

What you can do:

Put all instructions that have to do something with your data in another function and call it on the anonymous function function(phpdata) { ... }.

Like this:

function dataLoaded(data) {
   // show data in dom elements
   // work with data, e.g. check for data["error"] = true or show the username from data["username"]
}

data = [];
$(document).ready(function() {
  // Load JSON from server, wait for it and then work with it in dataLoaded(..)
  $.getJSON('database.php', function(phpdata){
      dataLoaded(phpdata);
  });
}
// this is wrong:
// console.log(data);

It is required that database.php will return an JSON array in the JSON data type. See json_encode and header("CONTENT-TYPE: application/json") on the php manual.

Thanks to the comment for saying: failed case sensitive and data type.

  • 1
    That should be `header('Content-Type: application/json')` (note that PHP instructions are case-sensitive). – Marcel Korpel Nov 21 '13 at 23:06
  • Just one little thing: [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Marcel Korpel Nov 21 '13 at 23:09
  • I get that point :-) Didn't talk about an object, just about "JSON array" what is not technically and definitionally right, too. – Dennis Ziolkowski Nov 21 '13 at 23:12
  • I tryed this, but i doesnt seem to work anyways =/. – Bobbie Nov 21 '13 at 23:37
  • Like this?: $(document).ready(function() { var arr = []; function pass(arr) { var arr = []; $.ajax({ url : 'database.php', dataType : "json", success : function(json) { console.log(json); arr = json; console.log(arr); return arr; } } ); }; console.log(arr); – Bobbie Nov 21 '13 at 23:38
  • If i use this: array = []; function callback(arr) { array = phpdata; }; $.getJSON('database.php', function(phpdata){ // vad du vill göra här, allt retuneras i data-variabeln callback(phpdata); }); It just says phpdata is not defined. Can i somehow make this array global so i can use it in my entire JS file? – Bobbie Nov 21 '13 at 23:48
  • You need to change `callback(arr) { array = phpdata; }; ` to `callback(arr) { array = arr; };` and REALLY work with arr only. And only in the callback function! Sorry, no way around since it is async – Dennis Ziolkowski Nov 21 '13 at 23:51
0

What does database.php do? It should probably be outputting a JSON encoded string.

http://us3.php.net/json_encode

Drumbeg
  • 1,914
  • 1
  • 15
  • 22