Skip to content Skip to sidebar Skip to footer

How To Pass Variable From JavaScript To PHP Page Using XMLHTTP

Please read the description before marking it as duplicate. As far as I know, the way to pass data from JavaScript to PHP is through Ajax Call. My scenario is like this: Using PH

Solution 1:

Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)

<script type="text/javascript">
    function sendJSValsToPHP(){
        var xmlhttp;

        //These are the variables i am going to post to illustrate the example, what you want
        var var_1toPost = 1;
        var var_2toPost = 2;
        var var_3toPost = 3;

        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                //You can get the response text from abc.php file and process it in any of the tags you want by javascript code
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;              
            }
        }
        xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
        xmlhttp.send();
    }
</script>

The echo'ed data in abc.php will come in the div="myDiv" //as a response.

<body>
    <div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
        the things echo'ed in abc.php will come in this div
    </div>
    <button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>

and then in abc.php //file

<?php
    $recieved_1 = $_GET['recieve_1'];
    $recieved_2 = $_GET['recieve_2'];
    $recieved_3 = $_GET['recieve_3'];

    //Do your processing here and insert it in the database
        //Insert Query OR Update Query (whatever)
    // after you have inserted you can get the response in
    // the <div> having id="myDiv" Or whatever you want
    // Suppose you have successfully inserted data then 
    $insertedDataBoolean = true;
    if($insertedDataBoolean){
        echo "Data: " . $recieved_1 . ", " . $recieved_2 . 
        " and " . $recieved_3 . " inserted successfully.";
    }
    else{
        echo "Data-insertion error.";
    }
?>

Solution 2:

What you are asking for is an Ajax Post method.

You can either send your data to the php page via json array or form serialize.

The function returns the data "echoed" from the php page into the tag with a class of result

$.post("path/yourPhpPage.php",{key: 'value'}, function( data ) {
  $( ".result" ).html( data );
});

Post a Comment for "How To Pass Variable From JavaScript To PHP Page Using XMLHTTP"