I’m banging my head for some hours now. I have a select option that it updates a database using AJAX (at least it’s trying to!). What happens is while running the PHP script directly with params required the database gets updated but not when running indirectly through AJAX, instead I get 3 times the alert("There was a problem in the returned data:\n"); and then it gets updated. JavaScript is on <head> and not in an external file. Here it goes:
JavaScript:
function updateHub(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
}else{
alert("There was a problem in the returned data:\n");
}
}
var prefHub = document.getElementById("prefHub");
var hubID = prefHub.options[prefHub.selectedIndex].value;
xmlhttp.open("GET","updateHub.php?hubID="+hubID,true);
xmlhttp.send();
}
updateHub.php:
session_start();
include '../../../common/config.php';
$hubID = '';
if(isset($_POST['hubID'])){
$hubID = strip_tags(mysql_real_escape_string(trim($_POST['hubID'])));
}elseif(isset($_GET['hubID'])){
$hubID = strip_tags(mysql_real_escape_string(trim($_GET['hubID'])));
}
mysql_query("UPDATE prefs set hubID='$hubID' where userID = '".$_SESSION['userID']."'") or die(mysql_error());
if(mysql_affected_rows()){
echo "Updated";
}else{
echo 'Error';
}
return $hubID;
and the HTML:
<form action="" method="post" onsubmit="updateHub();">
<select name="prefHub" id="prefHub">
<option value="43">opt1</option>
<option value="64">opt2</option>
<option value="30">opt2</option>
</select>
<input type="submit" name="update" value="Update Hub"/>
</form>
<div id="hubinfo"></div>
This means that you will always see the alert. Since for any other xmlhttp.readyState values the else {} block will be executed.
The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:
UNSENT (numeric value 0)
OPENED (numeric value 1)
HEADERS_RECEIVED (numeric value 2)
LOADING (numeric value 3)
DONE (numeric value 4)