0

I have file php that send value in array by query to ajax.

$sql = "SELECT * FROM populasi INNER JOIN waktu ON populasi.idWaktu = waktu.id WHERE waktu.jam = $jam";
$result = $con->query($sql);
$points=array();
foreach ($result as $m) {
    $points[] = 'new google.maps.LatLng('.$m[x].', '.$m[y].')';
}
print_r($points);

this ajax will receive a value from php file and I want the value to be a javascript array like "var points". Can you help me how to do it ? Thanks

$.ajax({
    type: "POST",
    url: "proses.php",
    data: {
      jam: slider.value,
    },
    success: function(response){
        //example array points
        var points = [
          new google.maps.LatLng(-7.320339, 112.768071),
          new google.maps.LatLng(-7.320233, 112.768446),
        ];
    }
});
shriek
  • 5,605
  • 8
  • 46
  • 75
  • you can [json_encode](http://php.net/manual/en/function.json-encode.php) the array and receive [json as response from ajax](https://www.lennu.net/jquery-ajax-example-with-json-response/). Then you can process the array data as you wish – Nikos M. Nov 15 '18 at 08:51

2 Answers2

0

can you please try below code The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.get response and used to your javascript code

<?php  $json_points = json_encode($points); ?>
Abhijit
  • 931
  • 1
  • 9
  • 21
  • its work, but the value in the array sent is a string because I don't know how to send it not in string form. I want the value of the array to be like "var points". can you help me how? – Ehsar D. M. Nov 15 '18 at 09:14
  • @ i am not get you comment .can you please explain briefly – Abhijit Nov 15 '18 at 09:17
0

A good solution for this is to convert data to JSON format in php and pass it to your js code

in your php:

$sql = "SELECT * FROM populasi INNER JOIN waktu ON populasi.idWaktu = waktu.id WHERE waktu.jam = $jam";
$result = $con->query($sql);
$result = json_encode($result);
echo($result);

in js:

$.ajax({
  type: "POST",
  url: "proses.php",
  data: {jam:slider.value,
  },
  success: function(response){
    response=JSON.parse(response);
    var points=[];
    for(var i=0; i<response.length; i++){
        var responsePoint=response[i];
        points.push(new google.maps.LatLng(responsePoint.x, responsePoint.y));
    }
  }
});