I'm trying to do game of Hangman I did in PHP in javascript using AJAX so that there is no need to reload the page while playing. However, I'm running into a problem. I'm trying to access the output of a PHP script that gives me a random word via AJAX. However, it's not working. I'd try doing this in Javascript but my class textbook has nothing about file access in Javascript and I'm having a hard time finding a good resource online. Here's my code.
<?php
session_start();
$stuff = $_SESSION['id'];
?><html>
<head>
<title>Javascript Hangman</title>
<script type = "text/javascript">
function processData(){
//alert("Actually in ProcessData block");
var httpRequest;
var type = arguments[0]; // get type of call
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
// Set data to submit to server, based on the type of the action
var data;
if (type == 0)
{
data = 'type=word';
//alert(data);
}
httpRequest.open('POST', 'getword.php', true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = function()
{
//alert("In httprequest block");
//alert(httpRequest.responseText);
//word = httpRequest.responseText;
if (httpRequest.readyState == 4)
{
if (httpRequest.status == 200)
{
return httpRequest.responseText;
}
}
alert(httpRequest.responseText);
};
//else
//other requests
httpRequest.send(data);
}
</script>
</head>
<body>You're logged in.
<script type = "text/javascript" language = "javascript">
var userid = '<?=$stuff?>';
var word = processData(0);
document.writeln("User id = ", userid);
document.writeln("Word = ", word);
</script>
</body>
</html>
Sorry if it's kind of sloppy, we only got a handout and a single example on how to handle AJAX, and I've already tried a bunch of different things to try to get this work as evidenced by the commented out code. Whenever I run it, word comes out undefined, although if I have the alerts enabled, it comes up with the output of the php script.
Posts
The words are stored in a flat file.
I don't think the 'return httpRequest.responseText;' in your anonymous function is gonna return from your processData function, it's only going to return from itself.
That line in the anonymous function :
//word = httpRequest.responseText;
should assign the right value to word, if you can actually access word from there.