passing a javascript variable to PHP with xmlhttprequest

Viewed 8327

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

2 Answers

I've been trying work out, for sometime, how to pass quite a long string I have formatted in javascript into php to save in a file and I think I now have the answer. At least it works for me.

The variable 'str' is passed into 'getGame' from another function after it has been formatted. I am using the 'POST' method as the string can get quite long. The code is:-

    function getGame(str){
    //Sends data to the php process "save Game".
    var test = str;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "saveGame.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
    xhr.onreadystatechange = function() {
        if (this.readyState === 4 ){
            alert(xhr.responseText);
        }
    };
    xhr.send("data="+ test); 
}

This sends the "data" to "saveGame.php where it is saved to a file as in the following code and returns a messsage in the alert dropdown.

<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
    $message = "Error writing to file. Try again later!" ;
}else{
    fwrite($fp, $outputString);
    $message = "File saved!"; 
}
fclose($fp);

echo $message;
?>

This works for me and I hope it is useful to other newbies.

Related