Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable from javascript to PHP

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?

like image 463
Hat Avatar asked Oct 16 '12 20:10

Hat


3 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'];
like image 154
FajitaNachos Avatar answered Oct 18 '22 11:10

FajitaNachos


Please try this:

We can pass a value from javascript to PHP.

we can use as,

$getValue = "<script>document.write(your script variable);</script>";
like image 42
VijayS91 Avatar answered Oct 18 '22 12:10

VijayS91


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)

like image 34
geocodezip Avatar answered Oct 18 '22 10:10

geocodezip