Use php to populate javascript array - php

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?

An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';

PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!

It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...

I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

Related

How to use outputs of php that is called by ajax in our file

I have an app that sends latitude, longitude values to my postgresql database. And i want to plot the updated points accordingly on my OpenLayers map using jquery,ajax. But here is where i am stuck at: When I click the button, the php file with database connection and saving the last entry of the table in an array is happening.
But when i try using the outputs in markers, nothing is happening.
How to use the output values of the php in my function?
Here is the code that i am trying to use.
php file:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
My page code is :
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
and the alert i am getting when clicking update button is
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
Is the way i am trying to access the values of query output correct? Please help.
Sorry if this is a dumb question. I am new to jquery.
When your php script sends a string like:
'var javascript_lat1 = ["output of the query"];'
back to your code, that does not mean that your code has a variable called javascript_lat1 in it.
Your php script is sending strings back to your javascript code from which you must extract the information that you want to use in your code. It is up to your javascript code to know what format the strings are in. But since you wrote the php script you can send the strings back in any format you want. Then your javascript code can dissect the strings with regexes, split(), etc. to extract the parts of the strings that you want to use in your code. A very simple format that your php code could use is:
"output of query 1, output of query 2"
Then you can split() on the comma to separate the two pieces of data e.g.:
var pieces = data.split(', ');
Then you can use pieces[0] and pieces[1] in your javascript code.
Another option is to send a request to your php script using the $.getJSON() function. If you do that, your php script should send back a json formatted string, e.g.:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
Then the $.getJSON() function will automatically convert the string into a javascript object and pass the js object to your callback function. Inside the callback function you can access the data using:
some_func(data.lat1, data.long1);

how to store php object to access its data on click with javascript

I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)

I have a variable that i need to send to php to be written to a file

I have a specific array that php needs to access and write to a file. I also want to be able to call the php to get the array info back. I use JSON.strigify to store the array in a string, but i cant figure out how to send it to a server with php. I have very little php experience and i tried:
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Have fun with this code: Chris');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
var new_name = $('#name').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
var arrayAsString = JSON.stringify(COMMENTS_FOR_DISPLAY);
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
duration: 5, // Time (ms) each blurb will remain on screen
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
in main.php i put:
<?php
$kwoteString = $_GET["arrayAsString"];
echo $kwoteString;
?>
I used echo to see if i was getting any output,but i wasn't. It could be a very simple fix, maybe im missing a header or something telling my html document to read main.php?? any help would be appreciated!
Use jquery with
$.post(url,params);
there are many tutorials around the web and stack overflow itself.
Here the doc:
http://api.jquery.com/jQuery.post/
you can add a hiddenField and set the string to the hidden field.
php code will read the value from hidden field.

Including JavaScript in PHP function Error

I had a weird problem here. Please check the code below. I do not understand how this code below is created by somehow part of it is working, considering mixture of php variables and javascript variables.
First, let us see what the alert() outputs (take note that $lat and $lng is different from the array $vlat):
In Line 8 of the code below, alert(eventlocation) properly displays the coordinates of the GoogleMap latlng (so the implementation is correct)
In Line 13, alert(s) was able to display incrementing values (i.e. 0,1,2,3,4,..) based on the for loop in the previous line so it is also correct.
In Line 14, alert($vlat[0]) was able to display the latitude of the first element of that array (declared before this set of codes) so it is also correct
In Line 15, alert($vlat[1]) was able to display the latitude of the second element of that array so it is also correct
But in Line 16, alert($vlat[s]) displayed undefined.
Can anyone explain that? Thanks
echo "<script src= 'http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA2jrOUq9ti9oUIF0sJ8it1RTNr3PHi_gURF0qglVLyOcNVSrAsRRu2C3WQApcfD0eh9NLdzf9My0b9w' type='text/javascript'> </script>
<script language='javascript' type='text/javascript'>
function getabc(){
var eventlocation;
var volunteerlocation;
var s;
eventlocation = new GLatLng($lat, $lng);
//alert(eventlocation);
var volunteerDist = new Array();
s = $ctr;
var tvid = new Array();
for(s=0;s<$numrows;s++){
//alert(s);
//alert($vlat[0]);
//alert($vlat[1]);
//alert($vlat[s]);
}
}
a = getabc(); < /script>";
alert($vlat[0]);
alert($vlat[1]);
alert($vlat[s]);
$vlat[0], $vlat[1] and $vlat[s] are parsed on the server before they is sent to the client. The first two can be resolved, but PHP does not know what s is, since s is only defined once the client side is reached.
Edit from chat discussion
$json = json_encode($vlat);
echo "<script language='javascript' type='text/javascript'>
function test(){
var obj = JSON.parse('$json');
alert(obj);
}
< /script>";
The variable s that you are using to index the PHP array vlat is a variable that you declared in JavaScript. You cannot use it to index a PHP array.
What your code tries to do is to have PHP access a JavaScript variable, which it cannot. You can have PHP echo JavaScript, yes, but it doesn't work both ways.

PHP to JSON on client side

I'm using Rob Monies 'Jquery Week Calendar' to build a calendar application.
I have a MSSQL DB a with table named 'dates' and the following fields:
id
start
end
title
I would like to query this DB in PHP and then pass the results to Javascript, Javascript will then render the events in the browser.
The Javascript needs to receive the event details in JSON format as per the following example:
{"id":1,"start": 2010-10-09T13:00:00,"end":2010-10-09T14:00:00,"title":"Lunch with Mike"},
{"id":2,"start": 2010-10-10T13:00:00,"end": 2010-10-10T14:00:00, "title":"Dev Meeting"}
So far, to keep things simple I've just returned one row from the DB at a time, however - I will need the application to be able to render multiple events, as stored in the database.
I've tried using json_encode() to put the values into a var and pass them to a Javascript var called DB_events - if I return the DB_events in an alert box on the client side I see the following;
{"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"}
which looks ok, but when I do this in my code:
events : [DB_events]
It doesn't work :(
If I take PHP out of the equation, and just do the following on the client side:
var DB_events = {"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"};
and return DB_events in an alert box, I get:
[object] [Object]
But when I do this:
events : [DB_events]
it works!
Back to PHP …
If I put the SQL result into PHP vars as follows:
$id = id;
$start = start;
$end = end;
$title = title;
and pass those vars to the following JS vars:
JS_id
JS_start
JS_end
JS_title
and do this on the client side:
var DB_events = {"id":JS_id, "start":JS_start, "end":JS_end,"title":JS_title};
events : [DB_events]
that also works.
As you can probably tell - I'm new to this and probably missing something very basic.
Any help, advice or information would be very much appreciated :)
Many Thanks
Tim
when you get a string representation of your object it means that you've exported it as a string not as an object.
when you get [object] [Object] it means that it is now an object, which is right!
You can do this with JSONP if you get JSON from an URL:
// send the request via <script> tag
var src = "..."; // url of the JSON output
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
Or parse it as a string with JSON parser:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var DB_events = JSON.parse( ...JSON output as a string... );
Or by directly passing it from PHP with an inline <script> block in your page:
echo "<script>";
echo "var DB_events = " . json_encode( ... ) . ";";
echo "</script>";
​
Did you use jsocn decode
http://php.net/manual/en/function.json-decode.php
You can split the result and make it differenct variables like start ,end , events etc
http://php.net/manual/en/function.explode.php

Categories