Basically what I'm trying to do is have a text field where the user enters in a foodstuff, and as theyre typing a message updates to say whether or not said item is in stock (through contacting the database).
My php code for the xml:
require 'connect.php';
header('Content-Type: text/xml');
echo "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo '<response>';
if (isset($_GET['foodInput'])&&!empty($_GET['foodInput'])) {
extract($_GET);
$sql = "SELECT * FROM food WHERE name=:foodInput";
$stmt = $db -> prepare($sql);
if ($stmt ->execute(array(':foodInput'=>$foodInput))) {
if ($stmt -> rowCount()>0) {
$results = $stmt -> fetch(PDO::FETCH_OBJ);
echo 'Yes, we do in fact have '.$results->name.'.';
}else{ echo 'No, '.$foodInput.' is not available champ.'; }
}
}else{ echo 'Please enter foodstuff.'; }
echo '</response>';
My Javascript for the rest:
function createHttp(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
};
return xmlhttp;
}
var xmlhttp = createHttp();
function handleServerResponse(){
if(xmlhttp.readyState==4){
if (xmlhttp.status==200) {
xmlResponse = xmlhttp.responseXML;
xmlDoc = xmlResponse.documentElement;
message = xmlDoc.firstChild.data;
document.getElementById('updated').innerHTML = message;
setTimeout(process, 1000);
};
}else{
alert('Something is amiss');
}
}
function process(){
if (xmlhttp.readyState==4||xmlhttp.readyState==0){
food = encodeURIComponent(document.getElementById('food').value);
xmlhttp.open('GET', 'include/foodstore.php?foodInput='+food,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.send();
}else{
setTimeout(process, 1000);
}
}
As soon as the process is initialised I get the alert something is amiss message that occurs when readyState is no longer 4. I entered a console.log(xmlhttp.readyState) and the resulting log was basically 1234123412341234 etc. So instead of sticking it out at 4 it would do something, else? Honestly I'm not particularly sure what readyState is.
When I remove this alert and I'm allowed to enter text it updates as the purpose requires. But as soon as the alert is turned back on, bingo there it is again.
Any suggestions? Really new to this area.
Thanks
Edit: Html
<form action="">
<label for="food">Enter foodstuff:</label>
<input type="text" id="food" name="foodInput" onkeyup="process()"><br>
</form>
<h4 id="updated"></h5>