0

I am stuck with getting an array from php function located in another file to a javascript. I used the below code but nothing is happening.

PHP code:

$sprd_array;
$spread = 0;
    foreach ($data as $key => $value) {
        $spread =(int) ($value->ask*100000) - ($value->bid * 100000);
        $spread =(float) $spread / 10000;
        $spread = round( $spread, 5, PHP_ROUND_HALF_UP);
        $sprd_array[] = $spread;
    }
    for($i = 0;$i < sizeof($sprd_array); $i++){
        //echo "spread: " . $sprd_array[$i] . "<br />";
    }
    return $sprd_array;
}

I want to get the array in another javascript file.

javascript code:

$.ajax({
    url:'jsondecode.php',
    complete: function (response) {
        alert("done");
    },
    error: function () {
        alert("error");
    }
});
return false;
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Kevin k5
  • 99
  • 1
  • 2
  • 9
  • Have you checked the console for errors? – Rory McCrossan Feb 19 '15 at 15:50
  • Your PHP code has **OUTPUT** your value. a `return` doesn't output anything. `echo json_encode($sprd_array)` would do the trick. echoing out the array directly would just produce the literal word `Array`. – Marc B Feb 19 '15 at 15:52
  • would you please explain with a code. I didn't understand you very well sorry – Kevin k5 Feb 19 '15 at 15:56
  • possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – Jon Surrell Feb 19 '15 at 16:00
  • its not a duplicate. I checked the link. It is different – Kevin k5 Feb 19 '15 at 16:03

3 Answers3

0

Do it like

$.ajax({
      url:'jsondecode.php',
      dataType : json,
      success: function (data) {
         console.log(data); // This is the data you want.
      },
      error: function () {
          alert("error");
      }
  });
void
  • 36,090
  • 8
  • 62
  • 107
0

In PHP, use the function json_encode() to encode your objects / arrays to JSON Format. Note that setting the second argument to true will keep associative array indeces.

Also, your JavaScript code is not alright. You need to use success: instead of complete:. Then, you can easily convert the string back into an object using JSON.parse(yourJSONString);.

Tacticus
  • 561
  • 11
  • 24
0

In php change "return $sprd_array;" to:

echo json_encode($sprd_array);
n-dru
  • 9,285
  • 2
  • 29
  • 42