Dynadot

Arrays in PHP and JavaScript

Spaceship Spaceship
Watch
Impact
38
I have looked about the net for help on this but cannot find an example which is unique to this situation.

I want to return the array list from a php file to javascript as an ajax response (using jQuery) for inclusion in a Flot graph.
This is using 'sample' data, the real data will be retrieved from a database and populate $array.

getAccounts.php
PHP:
$array = array(
0 => array(-373597200000, 315.71),
1 => array(-970918800000, 957.45)
);
echo $array;

accounts.php
PHP:
$(function () {
var d;
   $.ajax({
      type: "GET",
      url: "include/getAccounts.php",
      success: function(msg){ 
         d = msg;
      }
   });

    //d = [[-373597200000, 500.71], [-370918800000, 317.45]]; 

//The array is used here requiring d[i] to populate graph
    
});

The problem I am getting it the PHP is echoing the string 'Array' (which is expected when using echo), if i do 'echo $array[0][0]' it is getting the correct value.

The issue here is how to pass all the $array data into the javascript so it can be read properly.

The line "d = [[-373597200000, 500.71], [-370918800000, 317.45]];" works as required when uncommented so this is the form I need the array inside the JavaScript.


Does anyone know the best way to do this?

Much much appriciated!
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
solved by passing a string then using split() to rebuild the array in javascript.

Probably not the best way but it's working for now.

If anyone can provide a more efficient way let me know.

Thanks
 
0
•••
You would probably want to use JSON for this.
I would convert the php array to JSON using json_encode.
I would then retrieve the data from getAccounts.php in jQuery (which is what I think you're using) using .getJSON.

It makes it really easy to transfer the array over using standard methods. (Think both links I gave have examples on then, let me know if you need a hand with any of it :))
 
1
•••
Thanks a lot.
I had heard a few people mention using JSON but having not used it before I avoided it. I'll give it a go with those links you gave.
 
0
•••
Without DOUBTS use JSON.

You will find SO MANY tasks easier that it's worth starting somewhere and this is the PERFECT place.
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back