Pass variable from javascript to PHP

I use Google Maps to create a map that can load markers with lat / lng data stored in the database. I want you to have three different layers that the user can load by clicking the buttons. When the button is pressed, the php function is executed on the server, which creates an xml file from the information in the database. Then the AJAX function is called to pull the xml data, which is then used to create map markers. Instead of having separate PHP functions for each "level" (which would be the same except for a string with an SQL query), is there a way to pass a variable from javascript to AJAX to PHP?

+4
source share
5 answers

If you use AJAX, it is very easy for you to pass variables to the php file. Here is a brief 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 easily access variables using

  $ajax_var1 = $_POST['variable1']; $ajax_var2 = $_POST['variable2']; 
+8
source

Please try the following:

We can pass value from javascript to PHP.

we can use as,

 $getValue = "<script>document.write(your script variable);</script>"; 
+6
source

If you run an ajax get request with the following url

 somePhpFile.php?varName=10 

Inside your somePhpFile.php you can do

 $v = $_GET['varName']; 
+1
source

Here is a textbook by Mike Williams (v2) on AJAX Philosophy , where he does exactly what you ask.

(I should note that the map uses the Google Maps API v2, but this concept does not depend on the version of the API)

+1
source

Quote from Vijay S:

Please try the following:

We can pass value from javascript to PHP.

we can use as,

$getValue = echo "<script>document.write(your script variable);</script>";

Changed a bit, this worked well for me:

 $getValue = "<script>document.write(YourVarHere);</script>"; echo $getValue; 
+1
source

Source: https://habr.com/ru/post/1440141/


All Articles