I'm using Google Maps to make a map that can load markers with lat/lng data stored in a database. I want there to be three different 'layers' that the user can load by clicking buttons. When the button is clicked, a php function is executed on the server creating an xml file from the information on the database. An AJAX function is then called to pull this xml data that is then used to create the map markers. Rather than have separate PHP functions for each 'layer' (which would be the same thing except for the line with the SQL query), is there a way to pass a variable from the javascript in the AJAX to the PHP?
5 Answers
If your using AJAX requests it's pretty easy to pass variables to a php file. Here is a quick example.
$('#your-button').on("click", function(){
var somevar1 = "your variable1";
var somevar2 = "your variable2";
$.ajax({
type:"POST",
url: "your-phpfile.php",
data: "variable1=" + somevar1 + "\u0026variable2="+ somevar2,
success: function(){
//do stuff after the AJAX calls successfully completes
}
});
});
Then in your php file you simple access the varables using
$ajax_var1 = $_POST['variable1'];
$ajax_var2 = $_POST['variable2'];
2 Comments
Here is Mike Williams' (v2) tutorial on "The AJAX Philosophy", where he does exactly what you are asking about.
(I should note that the map uses Google Maps API v2, but this concept is not API version specific)
Comments
Quote From Vijay S :
Please try this:
We can pass a value from javascript to PHP.
we can use as,
$getValue = echo "<script>document.write(your script variable);</script>";
Modified a little bit it worked good for me :
$getValue = "<script>document.write(YourVarHere);</script>";
echo $getValue;