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

6.3k Views Asked by At

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 ] ];
5

There are 5 best solutions below

4
On BEST ANSWER

Include dataType: 'json'

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

The opposite of your json_encode PHP function in Javascript is JSON.parse(json):

var myArr = JSON.parse("[ [ 20 , 20 ],[ 20 , 30 ],[ 50 , 35 ],[ 40 , 20 ] ]");
2
On

simple do

data  = $.parseJSON('[ [ 20 , 20 ],[ 20 , 30 ],[ 50 , 35 ],[ 40 , 20 ] ]');

or

data = $.parseJSON(html);

NOTE: remove var while assigning array to data variable, it will assign the array to global data variable.

So final script will be:

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

Have you tried adding - "dataType: "json" to your ajax call.. If you do this, json_encode in your php script will take care of returning proper array structure.

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

instead of echo json_encode($return); you can use echo json_encode(array('data'=>$return)); to get response in associative array format.