Search code examples
phpajaxxmlhttprequest

passing a javascript variable to PHP with xmlhttprequest


Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?

// Get Cookies
var getCookies = document.cookie;
cookiearray  = getCookies.split(';');

SelectedIds = cookiearray[0];

//take key value pair 

 name = cookiearray[0].split('=')[0];
 value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass

// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();

hr.open("POST", url, true);
var url = "page.php";

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("Comp").innerHTML = return_data;
    }
}

hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";

PHP

 $test = $_POST['value'];
 print_r($test); // NULL

Thanks


Solution

  • Instead of

     print_r($test);
    

    use the echo

     echo $test;
    

    As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.

    And your send function in ajax should be like this:

    hr.send("value="+value);
    

    In the send function, the parameter that passed must be a string like this:

    "name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
    

    More tutorial is here.