I have tried for hours to get this script to work and i have come to the conclusion, it does not do want i want.
These scripts are asyncronous, which i think mean they are running all the time. My captcha code that i was trying to validate using the code by performing a lookup on a php file (validatecaptcha.php) was resonable successful.
My code
<!-- validate the code via ajax using validate.php to perform the validation --> <script> var interval; var result = null; // function myFunction(response){result = response;} // Alert the value of result and clear interval function getResult() { // once we get a result, turn interval off. if(result != null) { interval = clearInterval(interval); alert(result); // we're clearly out of the onreadystatechange scope with our result. } } function validateCaptchaCode() { result = null; enteredCaptchaCode = document.getElementById('ct_captcha').value; var xmlhttp = new XMLHttpRequest(); // actually POST the data (GET is slighlty different syntax) xmlhttp.open("POST", 'handlers/validatecaptcha.php', true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("enteredCaptchaCode=" + enteredCaptchaCode); // http://www.w3schools.com/php/php_ajax_php.asp xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // document.getElementById("txtHint").innerHTML = xmlhttp.responseText; // myFunction(); //myFunction(xmlhttp.responseText); /*if (xmlhttp.responseText == 'true') { alert("Stuff Working"); } else { alert("Stuff Not Working"); }*/ result = xmlhttp.responseText; } } // every second (1000 milliseconds) run getResult() interval = setInterval("getResult()", 1000); // this statement does not always work because xmlhttp.responseText is sometimes empty if (result == 'true'){alert('true code'); return true;} else {alert('false code'); return false;} } </script>
What Worked
- the actual loading of data from another page based on a POSTed variable
- validatecaptcha.php worked well, i posted a captcha to it and it returned 'true' or 'false' depending if the captcha was correct. I utilised $_SESSION with the rest of the captcha code, securimage.
- within the 'if section' (xmlhttp.readyState == 4 && xmlhttp.status == 200), you can easily access xmlhttp.responseText; you could also use the following and they would all work as expected inside the function. however you cannot get the response out of the function. you can do functions inside but not pass this information out to allow a condition based 'true / false' return. You can pass it to another function but again it is like a floated element outside of the normal DOM
- document.getElementById("txtHint").innerHTML = xmlhttp.responseText; - you can alter text on the page easily with this.
- myFunction();
- myFunction(xmlhttp.responseText)
- if (xmlhttp.responseText == 'true')........ with alerts on screen.
- result = xmlhttp.responseText;
- my if statement logic at the end for returning the validateCaptcha() works when it has the correct variables supplied to it
What doesnt work
- As mentioned already, you cannot pass information outside of the function. You can pass the information to another function but this function is also outside the normal flow
- you can pass the information to a global var (ie var result) but this seems out of sequence so you cannot utilise it for you own code. ie the function 'true / false' closing statement. It appears to maintain what was set in the global variable on the last cycle (i am using a session)
- this code also seems to run after the main function is completed, perhaps this is the asyncronious nature of it.
What would i use this for?
A good example is live updates for an autofill text box (PHP - AJAX and PHP - w3schools). This sort of coding should be considered a process unto itselfs.
You cannot use this for validating stuff if function exit state (true / false) depends on it.
You can use this for loading external content that will change the content on your page, like adding notifications. This will be independant of other javascript on the page.
Some Other Scripts
This is the one where i got the interval idea.
It is worth a read of this thread. Store responseText value to a global variable in JavaScript JavaScript and AJAX forum at WebmasterWorld . The interval setting might not make any difference in this example where i tried to use it to perfom validations. I think that all this does is pass the alert output down a function chain. Remember that httpobj.onreadystatechange occurs outside the normal Javascript runtime because it is asyncronous (run at the same time!).
http://www.webmasterworld.com/javascript/3952568.htm <script> var interval; var result = null; // Set this accordingly based on various return values from your PHP file httpobj = new XMLHttpRequest(); //FF for now httpobj.open('get', 'file.php', true); httpobj.send(null); httpobj.onreadystatechange = function() { if (httpobj.readyState == 4 && httpobj.status == 200) { result = httpobj.responseText; } } interval = setInterval("getResult()", 1000); // Alert the value of result and clear interval function getResult() { // once we get a result, turn interval off. if(result != null) { interval = clearInterval(interval); alert(result); // we're clearly out of the onreadystatechange scope with our result. } } </script>
This explains the issues i have had with this method and why
Return xmlhttp.responseText From AJAX Function - The SitePoint Forums
"The onreadystatechange function executes long after the other parts of the script have finished, so there is nothing to return anything to. Instead, you can pass the value to another function."