0

I tried here and here - without success

function abc() {
    var sky = 'blue';
    var earth = 'deep';
    var sun = 'gold';
    $.ajax({
        url: 'images.php',
        type: 'post',
        data: {'earth': earth, 'sun': sun, 'sky': sky},
        success: function(data) {
            // here I want new values as js array from php array
        }
    });
}

images.php

... some code...
$sky = "over";
$earth = "down";
$sun = "middle";

echo array($sky, $earth, $sun);

The above is very simplified example. In reality my variables inside php array are much more complex. So I don't want use the concatenation method on php side and split a string on js side.

  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – iainn May 21 '18 at 11:03
  • @iainn, already said - tried on that link - there is no such example. –  May 21 '18 at 11:08

2 Answers2

0

please use JSON to handle communication between PHP and JS. PHP should be doing:

echo json_encode($myArray);

and Jquery should be working with http://api.jquery.com/jquery.getjson/ most probably

Jan Myszkier
  • 2,714
  • 1
  • 16
  • 23
0

use json_encode to send data back to your JS Code.

Your JS side :

function abc() {
    var sky = 'blue';
    var earth = 'deep';
    var sun = 'gold';
    $.post('images.php', {'earth': earth, 'sun': sun, 'sky': sky}).done(
        function(json) {
            data = JSON.parse(json);
            //use data
        }
    });
}

images.php:

$sky = "over";
$earth = "down";
$sun = "middle";

echo json_encode(array($sky, $earth, $sun));
xanadev
  • 751
  • 9
  • 26
  • Thanks, I will try. Just - is it possible to write the same following the structure of `ajax - success` function ? –  May 21 '18 at 11:17
  • 1
    yes you can, that's the traditional way of handling the jquery success callback, but since the implementation of $.Deferreds and more sophisticated callbacks, done is the preferred way to implement success callbacks. – xanadev May 21 '18 at 11:21