0

I don't know how to make a script for sending multiple variables from external php to javascript (jQuery) For exemple:

<?php
  $test = "tets"; -->this, I want something this, no echo
  $dock = "dock"; --
  echo $test; -->no, I don't want echo in PHP script
  echo $dock; -->no, I don't want echo in PHP script
?>

and JS

<script>
function(){
  $.post("url", {Some_Thing: "Some_Thing"}, function (data) {
  alert(data); --> no, I don't want echo in PHP script
  alert($test); --> this, I want something this, no echo
  alert($dock);
  }
}
</script>
The1JJF1
  • 15
  • 1
  • 7

2 Answers2

1

Use a data structure, e.g:

<?php
   $data = array('test', 'dock');
   echo json_encode($data);

Then in your JS

$.post('url', {...}, function (data) {
    alert(data[0]);
}, 'json');
  ^^^^^^^^--- tell jquery you're expecting back some json
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

you can just output your data in JSON format and then load the data to JavaScript using ajax like so:

<?

$arrayWithData = array('data1' => 123, 'data2' => 555);

echo json_encode($arrayWithData);

then call load the data using ajax:

$.ajax({
    'url' : 'php-data-script.php',
    'method' : 'get',
    'dataType' : 'json'
}).done(function(data) {
    // do whatever you want with the data
    console.log(data);
});
Petar Vasilev
  • 4,281
  • 5
  • 40
  • 74