Hello guys, I need your help and here is the thing.
I used to use $_POST to submit a form and receive the data from a MySQL select query on the same page using PHP_SELF and usually it takes about one second to see the result. However the page always refreshes itself. In consideration of that I decided to use AJAX to send and receive data.
Well it does work, but it generally takes more than 3 seconds to received the data, which is something I did not expected. So could you please help? Here below is the code:
AJAX:
<script language="javascript">
function saveUserInfo()
{
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var userAge = f.user_age.value;
var userSex = f.user_sex.value;
var url = "./ajax_output.php";
var postStr = "user_name="+ userName +"&user_age="+ userAge +"&user_sex="+ userSex;
//var ajax = InitAjax();
var ajax = false;
if(window.XMLHttpRequest) { //Mozilla
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {//MiME
ajax.overrideMimeType("text/xml");
}
}
else if (window.ActiveXObject) { // IE
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ajax) { //
window.alert("Can not innitialize XMLHttpRequest.");
return false;
}
//Post
ajax.open("POST", url, true);
//HTTP header
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//POST DATA
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
msg.innerHTML = ajax.responseText;
}
}
alert (userName);
}
</script>
<div id="msg"></div>
<form name="user_info" method="post" action="">
Name:<input type="text" id="user_name"name="user_name" /><br />
Age:<input type="text" name="user_age" /><br />
Sex:<input type="text" name="user_sex" /><br />
<input type="button" value="Submit" onClick="saveUserInfo()">
</form>
Backend remains the same:
Select query
echo the result of query
Thanks so much!