blocjager
blocjager

Reputation: 77

How do I send a variable declared in JavaScript to the server side PHP script so that I can perform a SQL query using that variable?

This is my JavaScript code:

xmlhttp.onreadystatechange=function() 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    {
        for(i = 0; i < 5; i++)
        {
            var prikey = (i+1);
            //document.getElementById("demo").innerHTML = prikey;
            myFunction(xmlhttp.responseText);
        }
    }
}

xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(response) 
{
    //some code here
}

Now, I want to transfer prikey from this JavaScript file to the server-side PHP file.

The PHP code is

$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect"); 
mysqli_select_db($conn,"$db_name")or die("cannot select DB");

$sql="SELECT countries FROM $tbl_name";
$result=mysqli_query($conn,$sql);

I want to integrate the transferred prikey variable such that I will be able to query the database in the following way:

$sql="SELECT countries FROM $tbl_name where id=$prikey";

where $prikey is where I store the value gotten from the JavaScript file.

How do I accomplish this?

Upvotes: 2

Views: 368

Answers (1)

user4698813
user4698813

Reputation:

You need to add the prikey as a parameter to the GET url.

Javascript:

// The request is inside of a function so that each 
// xmlhttp is a different object
function sendRequest(prikey) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () 
    {
        if (xmlhttp.readyState === 4) 
        {
            if (xmlhttp.status === 200 || xmlhttp.status === 304) 
            {
                myFunction(xmlhttp.responseText);
            }
        }
    };
    xmlhttp.open("GET", url + '?prikey=' + prikey, true);
    xmlhttp.send();
}
// Send the requests
for(i = 0; i < 5; i++)
{
    // Pass it the prikey
    sendRequest(i + 1);
}

function myFunction(response) 
{
    // Do stuff
}

And in your PHP code, get it through the $_GET array:

// Get the variable sent through the Ajax request
$prikey = $_GET['prikey'];

$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect"); 
mysqli_select_db($conn,"$db_name")or die("cannot select DB");

$sql = "SELECT countries FROM $tbl_name WHERE id = $prikey";
$result = mysqli_query($conn,$sql);

// echo the result so that your JavaScript code gets the response
// Again, ignore if you've already done this
echo $result;

Upvotes: 2

Related Questions