I'm coding a plug-in for WP and I'm writing a JavaScript
script to the head
of the page document using php's echo
. I need to pass some php
variables to the script. I tried json.encode()
but it does not pass the right thing here is my function:
function test_action()
{
global $wpdb;
$contents = $wpdb->get_results("SELECT content FROM wp_map_user_demo");
$lats = $wpdb->get_results("SELECT latitude FROM wp_map_user_demo");
$longs = $wpdb->get_results("SELECT longitude FROM wp_map_user_demo");
//Modifying the header file of WP
echo '<title>Demo</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=myKey"></script>';
//Including the custom Google Maps script
echo "<script type='text/javascript'>
var map;
var contents = ". json_encode($contents) .";
var lats = ". json_encode($lats) . ";
var longs = " . json_encode($longs). ";
document.write('<p>' + lats[0] + '</p>');
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(lats[0], longs[0]),
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
}
//map.setOptions({draggable: true});
google.maps.event.addDomListener(window, 'load', initialize);
</script>";
}
When I open the page on WP document.write('<p>' + lats[0] + '</p>');
outputs [object Object]
on the page instead of latitude data.I checked the php variables and they are correct, so I guess that my problem is with JavaScript
usage.
Thanks for your helps...
document.write('<p>' + json_stringify(lats) + '</p>');
as your variable is json encoded and let us know what is output. – Code Lღver Jun 27 '14 at 8:41