javascriptphpjqueryajaxjquery-ajaxq

Loading Data From MySQL to JavaScript Array of Array Using jQuery Ajax


I have a php and jquery code like below

<script>
$( document ).ready(function() {
  var data =[];
    $("#submit").on("click",function(){
        $.ajax({
                type:"POST",
                url:"map.php",
                success: function (html) {
                    $('#message').html(html);
                }
        });
    });
});
</script> 

PHP

<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'test' );
  $con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
  $query = "SELECT x,y FROM app";
  $results = $con->query($query);
  $return = array();
  if($results) {
    while($row = $results->fetch_assoc()) {
      $return[] = array((float)$row['x'],(float)$row['y']);
    }
  }
   echo json_encode($return);
  $con->close();
 ?>

which return values from database like this in $('#message').html(html);

[ [ 20 , 20 ],[ 20 , 30 ],[ 50 , 35 ],[ 40 , 20 ] ]

How can I parse/export/push this result into data =[]; to have an array of array there so eventually the result looks like this?

var data  =[ [ 20 , 20 ],[ 20 , 30 ],[ 50 , 35 ],[ 40 , 20 ] ];

Solution

  • Include dataType: 'json'

    $.ajax({
         type:"POST",
         url:"map.php",
         dataType: 'json',
         success: function (html) {
             $('#message').html(html);
             data = html;
             console.log(data);
         }
    });