y45
y45

Reputation: 47

Get MySql data and store it into Javascript array

want to retrieve a records data from Mysql and store it into Javascript array for heatmap.js map data in this format :

var testData = {max: 46, data: [{lat: 33.5363, lon:-117.044, value: 1},{lat: 33.5608, lon:-117.24, value: 1},..]};

Now I get stuck at here, and I don't know how to connecting from Jquery into my var testData = new Array();, How I should do to solve this?

(UPDATED CORRECT CODE)

get_query.php

<?php
require_once('./db_con.php');
$dbcon=new db;


$query="SELECT (SELECT geo_lat FROM fun WHERE created_at <= DATE_SUB(NOW(), interval 1   minute) AS geo_lat," . 
       "(SELECT geo_long FROM fun WHERE created_at <= DATE_SUB(NOW(), interval 1 minute) AS geo_long";

$result = mysqli_query($dbcon,$query);
$data = array(); 

    while($row= mysqli_fetch_assoc($result)){

     $data[] = array("lat"=>$row["geo_lat"], "lon"=>$row["geo_long"], "value"=>1); 
     $post_data = json_encode(array('max' => 46, 'data' => $data));
    }
    echo $post_data;
 ?>

my_data.js based from here:

jQuery.extend({
getValues: function(url) {
    var result = null;
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data) {
            result = JSON.stringify(data);
        }
    });
   return result;
}
});

var testData = $.getValues("get_query.php");

Thanks to Orangepill and Chrislondon.

Upvotes: 1

Views: 9543

Answers (3)

nl-x
nl-x

Reputation: 11832

Your json seems incorrect:

var testData = {max: 46, data: [{lat: 33.5363, lon:-117.044, value: 1},{lat: 33.5608, lon:-117.24, value: 1},..]};

should be with quotes around the keys

var testData = {"max": 46, "data": [{"lat": 33.5363, "lon":-117.044, "value": 1},{"lat": 33.5608, "lon":-117.24, "value": 1},..]};

Since you use json_encode() in php I would assume PHP outputs this correctly. But maybe you are for now just working with a fixed (faulty) string for testing purposes?

Upvotes: 0

chrislondon
chrislondon

Reputation: 12041

So your question is how to connect your jQuery to your var data so I won't get into the myriad of problems in your PHP code. In your success function you can set the var data like so:

var data = new Array();

$(function() {
    $.ajax({
        type:     "post",
        url:      "get_query.php",
        data:     $(this).serialize(),
        dataType: "json"
}).done(function(response) {
    data = response;
});

Upvotes: 2

Orangepill
Orangepill

Reputation: 24665

while($row= mysqli_fetch_assoc($dbcon,$result)){
    $data[] = array("lat"=>$row["geo_lat"], "lon"=>$row["geo_long"], "value"=>1);
}
echo json_encode($data);

should get you what you are looking for. when building data for json_encode just use native php types instead of json, let json_encode take care of that

Upvotes: 3

Related Questions