Susanne92 Susanne92 - 3 months ago 9
PHP Question

Why doesn't javascript take my JSON array?

My php file ends with:

echo json_encode($array1);
echo ";";
echo json_encode($array2);


and prints out e.g.


[1358499135965,68];[1358499140000,2]


My javascript code looks so:

function requestData() {
$.ajax({
url: 'livedata.php',
success: function(point) {
var yenidata = point.split(";");
alert(yenidata[0]);
alert(yenidata[1]);
});
}


Why do I not get an alert?

Answer

Your JSON is not valid.

Try:

echo '[';
echo json_encode($array1);
echo ",";
echo json_encode($array2);
echo ']';

Now the PHP page will print you: [[1358499135965,68],[1358499140000,2]] Which can be parsed automatically as JSON using dataType:"json" in your ajax call.

When you include jQuery your code should look like:

function requestData() {
   $.ajax({
      url: 'livedata.php',
      dataType: 'json',
      success: function(point) {
         console.log(point[0]); //Array [1358499135965,68]
         console.log(point[1]); //Array [1358499140000,2]
      }
   });
}
Comments