how to use json_encode function of an array - javascript

I would like to select a specific line of an object that have been created using json_encode function from a php array.
while($locations=$req->fetch()){
$t = $locations->titre;
$la = $locations->latitude;
$lo = $locations->longitude;
$typ = $locations->type;
$ep = $locations->couleur;
$matrice[$i] = array($t, $la, $lo, $ep);
$i=$i+1;
}
var locations = <?php echo json_encode($matrice); ?>;
locations[0] = ['ma position actuelle', 0, 0, 0];
//console.log(Object.keys(locations));
//console.log(locations);
var centerLat=0.0, centerLong=0.0;
for (var i=1; i<Object.keys(locations).length; i++) {
centerLat+=locations[i][1];
centerLong+=locations[i][2];
}
I would like to select the second and the third element of "locations" but the syntax inside the loop is wrong. Does anyone has an idea.
Thank you

First you should do:
var locations = JSON.parse(<?php echo json_encode($matrice); ?>);
Then console.log(locations.toString()); to check your data
After, I think you're looking for Array.prototype.unshift() to add elements at the beginning of the array:
locations.unshift(['ma position actuelle', 0, 0, 0]);
(locations[0] = ['ma position actuelle', 0, 0, 0] just replace first item of the array)
then change you for loop
for (var i=1; i<Object.keys(locations).length; i++)
for
var i = 1, ln = locations.length;
for (i;i<ln;i++)

You can access any item in an JSONArray (or any Array) in JS like this:
object[i]
In your example, if you wanna get the second and third element:
for (...) {
var longitude = locations[i][1];
var latitude = locations[i][2];
}
But, I suggest that you use keys and make JSONObjects instead of just JSONArrays, like this:
$locations = array();
while($locations=$req->fetch()){
$location = array(
'titre' => $locations->titre,
'latitude' => $locations->latitude,
'longitude' => $locations->longitude,
... etc
);
$locations[] = $location;
}
That way you'll end up with a nice JSONArray filled with JSONObjects and you can call them from JS like this:
//locations is a JSONArray
var locations = <?php echo json_encode($matrice); ?>;
//locations[0] is a JSONObject
var latitude = locations[0].latitude;
var latitude = locations[0].longitude;

Related

Using PHP array in the JS code in PDO

I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.
I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_zagon = 1;
$id_kurat = 1;
$usid = 78;
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$gyvuliu_array = array();
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = $num;
}
$array_encode = json_encode($gyvuliu_array);
?>
<script>
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
I guess something is bad with the $num variable but I'm not sure.
EDIT:
I've changed the second for loop and it looks like it's working:
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m
EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array
Could You please try this once
$stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$row = $stmt1->fetch();
$array_encode = json_encode(explode(",",$row["nums"]));
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
Try this
var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:
// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);
// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
// Creating a PHP array
$gyvuliu_array = array();
// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = (int)$num;
}
// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
for (var i = 0; i < gyvuliai_fermoje.length; i++) {
// Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
}
</script>
I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Adding destination lat and lon to destinations variable distancematricx API Success and Fail

I'm trying to get the lat and lon from a Json encoded file for use as destinations for the distance Matrix API rather than add var destinationA = new google.maps.LatLng(??.????, ???.?????); multiple times.
I thought I managed it, as both ways seem to produce the same variable destinations when viewed, yet method two produces an error Uncaught TypeError: a.lat is not a function
This is method one which gives var destination a length of 7:
var destinationA = new google.maps.LatLng(13.7373393, 100.5558883);
var destinationB = new google.maps.LatLng(13.735132, 100.55611199999998);
var destinationC = new google.maps.LatLng(13.736953, 100.55819300000007);
var destinationD = new google.maps.LatLng(13.736244, 100.55694100000005);
var destinationE = new google.maps.LatLng(13.736166, 100.557203);
var destinationF = new google.maps.LatLng(13.738747, 100.55587700000001);
var destinationG = new google.maps.LatLng(13.733558, 100.56020699999999);
var destinations = [destinationA,destinationB,destinationC,destinationD,destinationE,destinationF,destinationG];
works great, will return the distances for each from a given centre point on google map.
Method two:
This is method Two which gives var destination a length of 1, which I am stuck on finding out why its a single length and not 7 as above:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
var first = true;
for (var i=0; i < location_lat_lon.length; i++) {
var sep = first ? '' : ',';
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(lat, lon);
var destinations = [destinations+sep+destination1] ;
first = false;
}
which returns exactly the same result when viewing the variable destinations, yet this returns the error Uncaught TypeError: a.lat is not a function.
Any advice or guidance?
Is it not possible to pass destinations this way to the calculateDistances function?
Thanks in Advance :)
Try this:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
for (var i=0; i < location_lat_lon.length; i++) {
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
destinations.push(destination1);
}

Populating 2D Array in JS

I am trying to popoulate a 2D array using Firebug API,
var sites = [];
var siteCounter = 0;
//Firebase API Calls
var messageListRef = new Firebase('https://my.firebaseio.com');
messageListRef.once('value', function(allMessagesSnapshot) {
allMessagesSnapshot.forEach(function(messageSnapshot) {
var latitude = messageSnapshot.child('latitude').val();
var longitude = messageSnapshot.child('longitude').val();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
siteCounter++;
alert(sites[siteCounter][1] + " " + sites[siteCounter][2] );
});
});
But this breaks for sites[siteCounter][0] and says it is undefined. Any clue how to work with this ?
if you want 2D array, you must to initialize like this :
var tab = new Array();
after
tab[0] = new Array();
Try this code
sites[siteCounter] = new Array();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
or directly
sites[siteCounter] = new Array("siteCounter", latitude, longitude, siteCounter, "This is siteCounter.");
Have you tried to do a
sites[siteCounter] = [];
before sites[siteCounter][0]?
I assume you have to declare it as an array to be able to put stuff in the array.

Parsing Javascript Array

I have an array as a attribute on a link.
Here is the array
images="["one.jpg","two.jpg"]"
How would I parse through this array and have it read back to me one.jpg,two.jpg?
This is what I am doing now and it is giving me an error back. I don't believe json parsing is whats needed here.
var imgs = $("#"+number).attr("images");
var imgList = jQuery.parseJSON(imgs);
EDIT: ACTUAL CODE
var number = $(this).attr("data-id");
var url = $("#"+number).attr("url");
$(".portfolio-url").html("<h3 class='pacifico'>url</h3><p><a href='http://"+url+"' target='_blank'>"+url+"</a></p>");
var cli = $("#"+number).attr("client");
$(".portfolio-client").html("<h3 class='pacifico'>client</h3><p>"+cli+"</p>");
var pgs = $("#"+number).attr("pages");
pgs = pgs.replace(/\[/g,"");
pgs = pgs.replace(/\]/g,"");
pgs = pgs.replace(/\"/g,"");
var pages = new Array();
pages = pgs.split(",");
var img = $("#"+number).attr("images");
img = img.replace(/\{/g,"");
img = img.replace(/\}/g,"");
img = img.replace(/\"/g,"");
var images = new Array();
images = img.split(",");
var portSkills = "<h3 class='pacifico'>skills</h2>";
portSkills += "<p>";
for (i=0;i<pages.length;i++) {
if (pages[i] != "Clients") {
var finalPage = "";
for (j=0;j<pages[i].length;j++)
{
var ch = pages[i].charAt(j);
if (ch == ch.toUpperCase()) {
finalPage += " ";
}
finalPage += pages[i].charAt(j);
}
portSkills += finalPage+"<br />";
}
}
portSkills += "</p>";
$(".portfolio-skills").html(portSkills);
var imgs = $("#"+number).attr("images");
var imgList = jQuery.parseJSON(imgs);
Basically, its looping through parameters
I'd encourage you to modify your attribute-value format to something along these lines:
<div id="one" data-images="file1.jpg,file2.jpg">Foo, Bar</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Note here I'm using a valid data- attribute, and the value of this attribute is just a list of comma-separated filenames. No need to place [ or ] in this value in order to get an array.
Now, to get your array:
var images = $("#one").data("images").split(",");
Which results in the following array:
["file1.jpg", "file2.jpg"]
Don't put that kind of string in the attribute, you could just put a comma separated string instead. (And you could use data attribute.)
For example:
<a id="foo" data-images="one.jpg,two.jpg">foo</a>
then you could get it by:
var imgList = $('#foo').data('images').split(',');
for (var i = 0; i < images.length; i++) {
var image = images[i];
}
For starters:
images = ["one.jpg", "two.jpg"]; is an array, yours is invalid.
to have it read back to you
for(image in images)
console.log(images[image]);
or the jQuery way
$.each(images, function(index){
console.log(images[index]);
});
if its a String that you need to split
then but that is of course if the string looks like this
var img = '["one.jpg", "two.jpg"]';
var images = img.replace(/\[|\]|"| /g,'').split(',');
this will give you an array parsed from a string that looks like an array.
Give the join() method a try:
images.join();
=> "one.jpg,two.jpg"
images.join(", ");
=> "one.jpg, two.jpg"
Edit: To declare your Array:
var images = ["img1", "img2", "img3"];
or
var images = new Array("img1", "img2", "img3");
Then you can use the join() method, and if that still doesn't work, try the following:
// should be true, if not then you don't have an Array
var isArray = (images instanceof Array);

JavaScript Array Formatting problem

Can someone assist me with formatting this JavaScript array correctly? I am obviously missing something fundamental:
Javascript:
<script type="text/javascript">
var widths = new Array("225","320","480", "--");
var sidewalls = new Array();
sidewalls["225"] = new Array("65","55","45","40", "--");
var rims["225"] = new Array();
rims["225"]["65"] = new Array("R17", "--");
rims["225"]["55"] = new Array("R17","R18", "--");
rims["225"]["45"] = new Array("R17", "--");
rims["225"]["40"] = new Array("R18", "--");
sidewalls["320"] = new Array("70", "--");
var rims["320"] = new Array();
rims["320"]["70"] = new Array("R20","R24", "--");
sidewalls["480"] = new Array("65", "--");
var rims["480"] = new Array();
rims["480"]["65"] = new Array("R28", "--");
</script>
PHP used to generate the above JavaScript:
<?php while($row = mysql_fetch_array($result)) {
list($width, $sidewall, $rim) = explode("/",$row['meta_value']); $menu[$width][$sidewall][$rim] = 1; }
$widths = implode('","', array_keys($menu));
print "var widths = new Array(\"$widths\", \"--\");\n";
print "\nvar sidewalls = new Array();\n";
foreach($menu as $width => $sidewall_array) {
$sidewalls = implode('","', array_keys($sidewall_array));
print "sidewalls[\"$width\"] = new Array(\"$sidewalls\", \"--\");";
print "\nvar rims[\"$width\"] = new Array();\n";
foreach($sidewall_array as $sidewall => $rim_array) {
$rims = implode('","', array_keys($rim_array));
print "rims[\"$width\"][\"$sidewall\"] = new Array(\"$rims\", \"--\");";
}
} ?>
Thank you in advance for your help
Stu
You shouldn't be putting var in front of array assignments, just the initial definitions.
So var widths = ... is fine, but var rims["225"] = ... is incorrect and should just be rims["225"] = ....
Change your php; in the line of code that outputs that text remove the "var". Change this:
print "\nvar rims[\"$width\"] = new Array();\n";
To this:
print "\nrims[\"$width\"] = new Array();\n";
That will solve your problem. But really, this overall solution is not the best. You ought to consider looking into the json-encode php method.
You can take a fully-structured php data structure and with this one command convert to something that can be read by javascript. Try replacing your php with the below and see what happens (note that this is untested, but this is the basic idea):
<?php
while($row = mysql_fetch_array($result)) { list($width, $sidewall, $rim) = explode("/",$row['meta_value']); $menu[$width][$sidewall][$rim] = 1; }
print "var widths = " . json_encode(array_keys($menu)) . ";\n";
print "var sidewalls = " . json_encode($menu) . ";\n";
?>

Categories

Resources