PDA

View Full Version : send / receive strings javascript php



.paul.
11-16-2013, 05:23 AM
i'm trying to send a string from javascript to php where the string will be written to a text file.
here's the relevant parts of the javascript:



<html>

<script type=""text/javascript"">
// Javascript

function getRequest() {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
return req;
}

function sendWords( wordsString ) {
var ajax = getRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
alert(ajax.responseText);
}
}
document.getelementbyid('frmOne').action="saveWords.php";

var jsonText = JSON.stringify(wordsString);
ajax.open("GET", "saveWords.php", true);
ajax.send("wordsString="+jsonText);

}

function getWords() {
var ajax = getRequest();
ajax.onreadystatechange = function(){
if(ajax.readyState == 4){
words = ajax.responseText;
}
}
ajax.open("GET", "readWords.php", true);
ajax.send(null);
}

</script>

<?php

?>
<FORM NAME="frmOne" id="frmOne" Method = "GET" Action = "">
</html>


at the moment, i'm still stuck trying to get the sendWords function working.
this is saveWords.php:



<?php
if(isset($_GET["wordsString"])) {
$jsonVal=json_decode($_GET["wordsString"]);
file_put_contents("filename.txt", $contents);
}
?>


when I can save the string variable, I also need to be able to read the file contents in php + retrieve the string in the getWords function.

this is readWords.php:



<?php
$file_handle=fopen("filename.txt", "r");
$returnString=fgets($file_handle);
fclose($file_handle);
return $returnString;
?>


can anyone help with this? thanks.