Forum Moderators: open

Message Too Old, No Replies

Need help - Why is Ajax so slow sending receiving data

         

mobilegame

1:57 am on Sep 4, 2017 (gmt 0)

10+ Year Member



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&#65306;<input type="text" id="user_name"name="user_name" /><br />
Age&#65306;<input type="text" name="user_age" /><br />
Sex&#65306;<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!

keyplyr

8:30 pm on Sep 6, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hi mobilegame, have you figured out the issue yet?

mobilegame

1:17 pm on Sep 7, 2017 (gmt 0)

10+ Year Member



Hello keyplyr, thanks for your reply. It has been solved. I actually had some issues with my MySQL queries which slowed down my website.