How to handle JSON that contains numeric strings - javascript

I am pulling JSON data from a webserver using the following PHP code
$result = mysql_query("select lat,lng from gpsdata limit 10");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);
I am using Javascript to get this data with this
$.getJSON('returngps.php').done(function(data) {
for (var i=0;i< data.length;i++ ){
console.log(data[i]);
}
}
My issue is the data I am getting returned. The output I am currently getting is:
{lat: "53.399793333333", lng: "-6.3844516666667"}
What I want to work with is:
{lat: 53.399793333333, lng: -6.3844516666667}
Is there a way to convert this?

The problem is that the retrieval of the numbers from MySQL to PHP results in them being cast as strings. (I HATE that the relationship between PHP and MySQL doesn't respect type!) The JSON serialization, then, appropriately maintains the string type.
As such, you need to cast the values to floats while retrieving. This will result in the JSON serialization treating the value as a number instead of a string, and won't require any ridiculous string manipulations, or assumptions about data type, in your receiving JS.
$result = mysql_query("select lat,lng from gpsdata limit 10");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$r['lat'] = (float) $r['lat'];
$r['lon'] = (float) $r['lon'];
$rows[] = $r;
}

Try using parseFloat:
data[i].lat = parseFloat(data[i].lat);
data[i].lng = parseFloat(data[i].lng);

Related

JS/PHP/MySQL Success but not Inserted

I have a array containing objects and I want to store these objects into my MySQL DB. At the beginning it worked quite fine, but suddenly it stopped working even though it did not make any changes to the code or the DB.
The array of object looks as follows: var geocoded = [{zip: 1234, place: "XY", country: "XY", lat: "123.123", lng: "123.123"}, ...];
I use the following JS code to iterate over the array and post each object to the DB. kiter is the iterator I use and is defined as geocoded.length - 1
function postPlaces(data, kiter) {
if (kiter >= 0) {
$.post("api/placessave.php",
data[kiter],
function(data, status){
kiter--;
postPlaces(geocoded, kiter);
console.log(data + '.............' + status);
}
);
} else {
//statusUpdate(id);
}
}
placessave.php looks as follows:
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','*****');
define('DB','****');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$zip = $_POST['zip'];
$place = $_POST['place'];
$country = $_POST['country'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sql = "insert ignore into places (zip, place, country, lat, lng) values ($zip, '$place', '$country', '$lat', '$lng')";
if(mysqli_query($con, $sql)){
echo "success";
}
mysqli_close($con);
?>
I use INSERT IGNORE because duplicates may exist but an update is not needed.
The interesting part is, that everything works quite nice I also get a Success on every query but nothing is stored to the DB.
Insert Query you have to change like this. You have Missed Quotes around the values
Replace
$sql = "insert ignore into places (zip, place, country, lat, lng) values ($zip, '$place', '$country', '$lat', '$lng')";
With
$sql = "insert ignore into places (zip, place, country, lat, lng) values ('".$zip."', '".$place."', '".$country."', '".$lat."', '".$lng."')";
I found the solution myself. The problem was in the data I wanted to store. I found that there was a place name which contained a '. Therefore the query did not work. After removing this, everything works fine.
just change ($zip, in the query to ('$zip',
zip is probably string and you are not passing it as string in the query. Moreover, this code is vulnerable to SQL injection. Please read about it to avoid insecurities.

Get a php array into a js array

I want to get a php array made by pg_fetch_all in a javascript array. But when I try to do it, firebug tells me that I'm trying to convert an array to string. Indeed, I don't understand why because both are arrays.
Here is where I create the php array :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT ".$colonne." FROM public.".$tablevar."";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And here is my js code :
var array_dropdown =[<?php echo $data;?>];
And it doesn't work. Please help me !
PHP Arrays 101: Arrays in a string context are the literal word Array:
$x = array(1 => 2);
echo $x; // ouputs "Array"
You need to use json_encode():
var array_dropdown = <?php echo json_encode($data); ?>;
json_encode guarantees that whatever you pass in to the encode function will be output as syntactically valid javascript. Note the lack of [] around the above code - json_encode handles all of that for you.
Assume this as your PHP array
$array = array('foo' => 'bar');
The JS part:
var array = <?php echo json_encode($array); ?>;

parse string element in JSON array to integer

$con = new DBConnector();
$sth = $con->Query("SELECT medicinename as label, factor as data FROM medicine_master_tbl limit 4");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
echo json_encode($rows);
there is no problem with my query,but the returned value is ..
[{"label":"rrp","data":"5"},{"label":"t","data":"34"},{"label":"tt","data":"4"},{"label":"nutrachin","data":"45"}]
i need the json array as like below..
[{"label":"rrp","data":5},{"label":"t","data":34},{"label":"tt","data":4},{"label":"nutrachin","data":45}]
which the data is considered as string in this array , i need to be parse it as integer .. thanks in advance.
An easy one.
while ($r = mysql_fetch_assoc($sth)) {
$r["data"] = intval($r["data"]);
$rows[] = $r;
}
Ideally your database connector would allow you to specify what type of data you are returning in the row, if factor is a numeric type. For instance, PDO and mysqlnd can return native types (see How to get numeric types from MySQL using PDO?).
However, you can do the following:
while ($r = mysql_fetch_assoc($sth)) {
$r['data'] = intval($r['data']);
$rows[] = $r;
}
This way, your JSON encoding will have an integer.

Storing data from MySQL to PHP Array to return with JSON

I have a MySQL table with cols | btn_id | btn_title | btn_bg | btn_text |.
I am trying to get the data in the table to a php array and then return via JSON so the array can be used in the JS document requesting the PHP/MySQL Data. Respective of row and columns/index.
So far i have:
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
Q. Now i wish to return a JSON Array made from the array of data. How do i proceed here?
Note: I am horrible with arrays and not entirely sure i have the correct method above for my requirements, but i think it is correct.
Call json_encode after the loop:
header("Content-type: application/json");
echo json_encode($array);

Manipulating JSON data to create javascript array of lat/lngs in Google Maps API V3

I'm trying to use lat/lng values retrieved from MySQL to create an array of waypoints for use in the GMaps API. I have the code below but with my limited javascript knowledge am struggling to push this retrieved data into a javascript array to define as the waypoints data.
I've looked at a few online examples and so far I have managed to get a parsing script to retrieve the data with no problems and call this within the page I have the maps instantiated on:
makeRequest('parsedata.php', function(data) {
var data = JSON.parse(data.responseText);
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
}
});
The parsedata.php code:
<?php
include 'session.php';
$query = "SELECT itinerary_link.itineraryID, itinerary_link.coursesID, itinerary_courses.coursename,
courses.lat, courses.lng FROM itinerary_link LEFT JOIN
itinerary_courses ON itinerary_link.coursesID = itinerary_courses.coursesID LEFT JOIN
courses ON courses.coursename = itinerary_courses.coursename WHERE itineraryID=6 ORDER BY coursename";
$result = mysqli_query($dbc, $query);
$rows = array();
while ($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode( $rows );
?>
And sample output from this:
[{"itineraryID":"6","coursesID":"20","coursename":"Carnoustie Championship Course","lat":"56.497414","lng":"-2.720531"},{"itineraryID":"6","coursesID":"21","coursename":"Troon Old Course","lat":"55.534203","lng":"-4.642833"}]
Basically I can't work out how to manipulate this output to create the required javascript array of lat/lngs to feed in as the waypoints for a directions service instance I have running on the page.
As always, any pointers much appreciated. Cheers.
//create an array for the waypoints
var waypoints=[];
//only up to 8 waypoints are allowed without business-license
for(var i=0;i<8 && i<data.length;++i) {
//push a LatLng-object to the array
waypoints.push(new google.maps.LatLng(data[i].lat,data[i].lng));
}
//use the waypoints
//doSomethingWith(waypoints);

Categories

Resources