Click here to Skip to main content
14,838,518 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Extracting data from mysql and using them in javascript, instead of an array with integer I get a string with quotes like this:

"var latlong = [[38.4870556,68.8065556],[38.7059167,69.2994444]];"


What I have tried:

Here extracting data with PHP:
try {
    $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, array(
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        PDO:: ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
        PDO:: ATTR_ERRMODE => TRUE
    ));

} catch(PDOException $e) {
    die($e->getMessage());
}

$stmt = $db->prepare("SELECT latitude, longitude FROM  hydros WHERE latitude <> 0");
$stmt->execute();

$data = [];

$result = $stmt->fetchAll();
foreach ($result as $row) {
    $data [] = [(float)$row->latitude,(float)$row->longitude];
}

echo "var latlong = " . (!empty($data) ? json_encode($data)  : "]") . ";";


Then retrieving data with jQuery
	function latlongc(callback) {
    httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4) { // request is done
            if (httpRequest.status === 200) { // successfully
                callback(httpRequest.responseText); // we're calling our method
            }
        }
    };
    httpRequest.open('GET', "latlong.php");
    httpRequest.send();
}

	latlongc(function (result) {
    
    latlong1 = result;
    console.log(latlong1);
});
Posted
Updated 7-Jun-19 6:34am
Comments
Richard MacCutchan 22-May-19 3:46am
   
Look at the last line of your php code, you present the result as a string.

Looking at that last line of php code:
echo "var latlong = " . (!empty($data) ? json_encode($data)  : "]") . ";";
Suppose the array is empty?   Your output would be:
var latlong  = ];
which is obviously an error and could cause collateral mischief in other javascript.

Suppose it's not:
If you build the page with the javaScript before the page is served they're part of the page. Use as normal.
If, however, you put javaScript on your page with AJAX, be aware that new javaScript may not be actually available to your page if you just render the text.

Let's assume callback() already exists: It's getting what you'd expect[^] form JSON formed from a non-associative array. By this I mean you do not have indices.

You'll find this in the linked page:
Quote:
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}


Hope this helps you find your missing int's (i.e., If I understand you correctly)
   
Comments
Himjon 7-Jun-19 12:36pm
   
Thanks, you triggered me to find the right solution.
W Balboos, GHB 7-Jun-19 13:10pm
   
Don't forget to mark the question answered so attention can be given elsewhere!
[no name] 18-Jun-19 10:48am
   
thanks
Building GeoJSON file to use it with javascript.
# Build GeoJSON feature collection array
$geojson = array(
   'type'      => 'FeatureCollection',
   'features'  => array()
);

# Loop through rows to build feature arrays
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $properties = $row;
    # Remove long, lat and IFNULL fields from properties (optional)
    unset($properties['IFNULL']);
    unset($properties['longitude']);
    unset($properties['latitude']);
    $feature = array(
        'type' => 'Feature',
        'geometry' => array(
            'type' => 'Point',
            'coordinates' => array(
                (float)$row['longitude'],
                (float)$row['latitude']
            )
        ),
        'properties' => $properties
    );
    # Add feature arrays to feature collection array
    array_push($geojson['features'], $feature);
}

header('Content-type: application/json');

//Building var hydros to add it 
$hydros = "var hydros = ";

//Write to geoJSON file
$fp = fopen('data/hydros.geojson',  'w');
fwrite($fp, $hydros);
fwrite($fp, json_encode($geojson, JSON_UNESCAPED_UNICODE));
fclose($fp);


Then using "var hydros;" array in javascript:

<script src="data/hydros.geojson"></script>


Hope this will help others.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900