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.
Related
After searching for internet and even here for 5 hours, i am still stuck at getting value of a local variable in a function and sending it to PHP.
I have tried different syntaxes but none of them seems to be working. This code below, takes an input field from PHP and assign some value to it (having problem send this value back to PHP)
$(document).ready(function() {
//select all the a tag with name equal to modal
$('form[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Dont go until value is not 7
console.log('i am Now waiting for input');
var s = $('#serial').val();
console.log('searching for ' + s);
while(s.length != 7) return;
//When code value reaches 7
var code = $('#serial').val();
console.log('Value is reached ' + s);
});
});
In PHP
echo "<script>document.write(code);</script>";
Uncaught ReferenceError: code is not defined
please help
You should do somthing like this in javascript when $('#serial') is your input field.
$.ajax({'url':'your_php_file_url', 'type':'post', 'data':{'str':$('#serial').val()}}).done(function(data){
console.log(data.code);
});
And in php
$output = Array('code' => 'not set');
if (isset($_POST['str']))
{
//do your search and assigne value to output
$output['code'] = 'some value';
}
echo json_encode($output);
In short - you send your search string via ajax to php and make your searches. Then you echo it out as json, then ajax will read it as an object and you can use those values you want.
ok, i have almost tested every possible solution but all in vain... so i am off and try to use some normal method rather than javascript. Thanks for all your answers guys.
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);
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.
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
?>
I m new to CakePhp and JQuery.
I am getting an error in using the cakephp code inside my JQuery.
My code
<script type="text/javascript">
$(document).ready(function(){
var attributeid;var fieldname;
$("#"+<?=$r['Attribute']['id'];?>).change(function () {
fieldname=<?=$r['Attribute']['label'];?>;
alert(fieldname);//this show me that undefined
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
});//attribute change
});//ready function
if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?>.
But not inside my JQuery.
Note :
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
Error:
Name is not defined
fieldname=name;
alert(fieldname);
You are not thinking about how this is translating over once the variables are echoed.
If you have a variable $x with the contents "test", doing this:
var x = <?=$myvar?>;
Will result in:
var x = test;
This is not valid (unless test is a variable) because you need quotations around it to make it a string:
var x = "<?=$myvar?>";
Which then results in the valid:
var x = "test";
The reason it works with the other variable is because you are echoing an ID, which is an integer:
var x = <?=$myid?>;
Would translate to:
var x = 5;
Which is perfectly valid.
All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.