Populating Google Map Markers from PHP array using json_encode - javascript

When I use the hard coded javascript array as input for the map markers the markers show up just fine, so I know that the code I'm using to display the markers is good.
My problem is when I try and convert a php multi-array using json_encode, nothing shows up on the map.
The hard coded markers are:
var locations = [
['Sausalito', 37.8590937, -122.4852507,'url'],
['Sacramento', 38.5815719, -121.4943996,'url'],
['Soledad', 36.424687, -121.3263187,'url'],
['Shingletown', 40.4923784, -121.8891586,'url']
];
and they work.
The php array is:
$locations = array(array(Sausalito, 37.8590937, -122.4852507,'url'),array(Sacramento, 38.5815719, -121.4943996,'url'));
which produces the array,
Array
(
[0] => Array
(
[0] => Sausalito
[1] => 37.8590937
[2] => -122.4852507
[3] => url
)
[1] => Array
(
[0] => Sacramento
[1] => 38.5815719
[2] => -121.4943996
[3] => url
)
)
so no problem as yet.
Now when I json_encode the above array
var locations = '<?php echo json_encode($locations); ?>';
it does not get read by the javascript map code. and if I print the variable
document.write(locations);
it shows up as
[["Sausalito",37.8590937,-122.4852507,"url"],["Sacramento",38.5815719,-121.4943996,"url"]]
which kinda looks like the hard-coded above, but it does not get read by the map code which works with the hard-coded data.
Can anyone assist me, please, much appreciated.

Remove the single-quotes, otherwise locations will be a string and not an array:
var locations = '<?php echo json_encode($locations); ?>';
//--------------^--------------------------------------^

Related

Can't select specific element in JSON parsed array with JavaScript

So I have a mySQL database and I am pulling data from it to my website and want to change content with the help of JavaScript. The problem is that I can't seem to select specific elements out of my data which I received from the databse.
Here is how I pull data and parse it into a JSON string:
while($row = $result->fetch_assoc()) {
$return_array = array("region" => $row['region'], "capital" => $row['capital'], "surface_area" => $row['surface_area'], "land_area" => $row['land_area'], "water_area" => $row['water_area'], "global_area_rank" => $row['global_area_rank'], "land_boundary" => $row['land_boundary'], "bordering_countries" => $row['bordering_countries'], "coastline" => $row['coastline'], "climate" => $row['climate'], "terrain" => $row['terrain'], "avg_elevation" => $row['avg_elevation'], "highest_elevation" => $row['highest_elevation'], "lowest_elevation" => $row['lowest_elevation'], "natural_resources" => $row['natural_resources'], "land_use" => $row['land_use'], "irrigated_land" => $row['irrigated_land'], "natural_hazards" => $row['natural_hazards']);
}
echo json_encode($return_array);
In my JavaScript method I call this PHP script and receive the parsed JSON string which I temporarily output in a single div:
$.post('ajax/retrieve_data.php', { sel1: sel1, sel2: sel2 }, function(data) {
var return_array = $.parseJSON(data);
$('div#test-div').text(return_array.region);
});
The output however, just shows the entire JSON string with curly brackets and all identifiers, which means that the return_array.region selector does not work. I tried it with indices and all sorts of other syntax, but it did not work. Everywhere on the internet everyone uses this syntax to select specific elements, but it somehow doesn't work. I probably have a very stupid error in there, but I appreciate every help. I just can't seem to see the error.
My guess is that your PHP script isn't returning data with the proper Content-Type header. Make sure, in your PHP script, you run the following:
header('Content-Type: application/json');
This must come before echoing anything.

JSON passes string instead of array or object from PHP to Javascript

I am having som trouble with passing a multidimensional and associative array from php to Javascript. I converte it with JSON, using:
_SESSION = '<?php print json_encode($_SESSION) ?>';
I have also tried
_SESSION = '<?php print json_encode($_SESSION, JSON_PRETTY_PRINT) ?>';
_SESSION = $.parseJSON('<?php print json_encode($_SESSION) ?>');
both of them give me errors like: Uncaught SyntaxError: Unexpected token ILLEGAL.
However, the first one doesn't give me any errors and I can access it in Javascript. It then outputs:
{"items":{"221163":{"CodeComplete":null,"Project":"Coding","Team":"Mail","TimeSpent":25","Children":[]}}, {"221165":{CodeComplete":null,"Project":"Coding","Team":"Batman","TimeSpent":"40","Children":[]}}
I belive this is like a string, since _SESSION[0] outputs "{". However, I want it to be an array or an object. The Array looks like this in php:
_SESSION( "items" => array(
221163 =>
array( CodeComplete => null
Project => "Coding"
Team => "Mail"
Timespent => "25"
Children => array(
)
)
221165 =>
array( CodeComplete => null
Project => "Coding"
Team => "Stones"
Timespent => "40"
Children => array(
)
)
)
)
I want to be able to access this array in the same way as I can in php (not litterary ofcorse) but _SESSION["items"] or _SESSION.items is undefined as _SESSION is a string...
Any ideas of what I'm doing wrong?
Just as #CD001 suggested in his comment, I removed the '' from the transfer so that it became
_SESSION = <?php print json_encode($_SESSION) ?>;
instead and now everything works fine, thank you!

Create and edit file javascript with "file_put_contents"?

i would like to create a file.js with php but i think that in my code there are a lot of errors:
i have multidimensional array:
$report= array();
$report= array(array(3,6),array(4,8));
that is:
Array
(
[0] => Array
(
[0] => 3
[1] => 6
)
[1] => Array
(
[0] => 4
[1] => 8
)
)
Set a content-type for js file
$header = "Content-type: text/javascript";
$dir = "outreport/";
$nomefile = "report.js";
//delete a file with same name if exists
foreach (glob($dir."*".$nomefile) as $v){
unlink($v);
}
$percorso = $dir.$nomefile;
file_put_contents($percorso, $report);
header($header);
print($report);
There are two problems:
1) when launching the file.php asks me to download the same file but in javascript
2) in the "outvulcani" it creates the file report.js but is empty
I wish that in the file "report.js" there is the array $report but
written in javascript code:
var reports = [
[3,6]
[4,8]
];
Kindly, you can help me out?
Thanks a lot!
Sorry for my english
PHP has an function to convert Arrays to JSON. You could use this code for "inspiration".
$report = array(array(3,6),array(4,8));
$javascriptContent = json_encode($report);
// Convert to string
$javascriptContent = "var reports = ". $javascriptContent . ";\n";
file_put_contents($percorso, $javascriptContent);
The reason for "Download" is the header, please remove it.

using AJAX query to pass javascript array to php

After reading through quite a few posts here, (and even just straight copying code,) I still cannot figure out why this is not working.
On my main page, I have a textbox that a user pastes data into. Upon paste, this script runs (this and the ajax query below are in the same script function):
var lines = $('textarea').val().split('\n'); //create array from pasted data
I now have a JavaScript array with the pasted data. I'm trying to send this over to a separate PHP file that I will load into a div on this main page by doing the following:
$.ajax({
type: 'POST',
url: 'return.php',
data: {lines:lines},
success:function(data){
$("#info").load("return.php");
}
});
for (i=0; i < lines.length; i++) { // log the output
if (lines[i]){
console.log("line ", i , lines[i]);
}
}
In my return.php file, I have this:
$lines = $_REQUEST['lines'];
echo '<pre>';
echo($lines);
echo '</pre>';
My console.log is outputting the array perfectly, but for some reason it is not making its way over to return.php, as my echo is blank.
What am I doing wrong?
The response I get from return.php is:
<pre>testArrayArray
(
[0] => DL4004-13-F
[1] => S1G-13-F
[2] => ZXMP3A13FTA
[3] => B260A-13-F
[4] => S1J-13-F
[5] => S3B-13-F
[6] => SSN1N45BTA
[7] => GBJ1010-F
[8] => BPW20RF
[9] => T3035H-6I
[10] => ZXMP7A17KTC
[11] =>
)
</pre>
The success handler on your ajax request is calling return.php with nothing and loading it into #info.
Change success to instead do:
$("#info").html(data)
The $lines variable in your PHP code is an array, not a string. If you have the errors turned on, PHP should warn you that you're doing an "Array to string conversion" (at least it does for me using your code).
You can't echo an array like that, you have to iterate through the results somehow.

how to make this javascript object from php json encode

hello i am trying to figure out how i would ago about pulling information from a database in php and json_encoding it ito a JavaScript object that contains several JavaScript arrays that themselves have children objects and arrays.
below is the JavaScript i need. ive been playing with embedding arrays into php objects but cant seem to get it to come our correctly.
self.navigation = [
{
menutext:"Home",
url:"/"
},
{
menutext:"About",
url: "#/about",
submenu:[
{
menutext:"Pricing",
url: "/pricing"
}
]
}
];
<script type="text/javascript">
var jsObject = <?php echo json_encode($phparray); ?>;
</script>
pretty self-explanatory i think, if you need the object a specific way it's about how you format your php array itself.
To get arrays within objects you use the object key and set it to an array like so:
$phpArray = array(
'magic' => array('elmo')
);
json_encoded an array will be within the "magic" object. In order to get the parent item as an array with objects inside i would just fudge it in the variable setting itself like so:
<script type="text/javascript">
var jsObject = [<?php echo json_encode($phparray); ?>];
</script>
To get submenu into array have you tried the following:
$phpArray = array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
array(
'menutext' => 'Pricing',
'url' => '/pricing')
)
);
Bit unintuitive I know. Actually to get exactly what you want without fudging it would be:
$phpArray = array(
array(
'menutext' => 'Home'
),
array(
'menutext' => 'About',
'url' => '#/about',
'submenu' => array(
array('menutext' => 'Pricing',
'url'=> '/pricing')
)
)
);

Categories

Resources