Reputation: 53
I am trying to accomplish simple yet seems complicated task. I am trying to make AJAX call from pure JavaScript (front end) to aspx page (back end) without including any asp ajax library aiming no asp page rendering on front end i.e. only html+JS for front end.
So here is how it goes, on the front end this js code will send asynchronous call to asp page with a variable. The variable is derived from text box value.
function handleRequest() {
if (xhr.readyState < 4) {
return; // The response is not available yet , we do nothing
}
if (xhr.status !== 200) {
alert('Error!'); // error HTTP
return;
}
}
function getValue() {
var textVal = document.getElementById("test1").value;
xhr.open('GET', 'WebForm1.aspx?q=' + textVal , true);
xhr.send();
var response = xhr.responseText;
document.getElementById("bdy").innerHTML = response;
}
var btn = document.querySelector("button");
var xhr = new XMLHttpRequest();
var body = document.getElementById("bdy");
xhr.onreadystatechange = handleRequest;
document.getElementById("header").innerHTML = Date();
btn.addEventListener('click', getValue, true);
Now, on the back end asp code which will echo the textbox value with the time stamp from the server.
protected void Page_Load(object sender, EventArgs e)
{
string getRequest = Request.QueryString["q"];
DateTime dt = DateTime.Now;
string responseText = getRequest + dt.ToString();
Response.Write(responseText);
}
Finally, this code works perfect when I make synchronous call i.e. xhr.open('GET', 'WebForm1.aspx?q=' + temp, false); but fails if I send asynchronous call i.e. xhr.open('GET', 'WebForm1.aspx?q=' + temp, true);
I would really appreciate your help.
Upvotes: 1
Views: 1500
Reputation: 15893
Code that uses data obtained by asynchronous operations should be placed in a callback invoked after the data arrives. You already have such callback function - handleRequest
:
function handleRequest() {
if (xhr.readyState < 4) {
return; // The response is not available yet , we do nothing
}
if (xhr.status !== 200) {
alert('Error!'); // error HTTP
return;
}
var response = xhr.responseText;
document.getElementById("bdy").innerHTML = response;
}
function getValue() {
var textVal = document.getElementById("test1").value;
xhr.open('GET', 'WebForm1.aspx?q=' + textVal , true);
xhr.send();
}
Upvotes: 1
Reputation: 53
I found the answer. The problem was that when doing the AJAX synchronous call, the browser would wait for the response from the server before storing the result to the variable response and hence display the results. However, when doing asynchronous call, the browser won't wait for the response and hence response variable will be null and the innerHTML will display nathing.
By adding a delay to the response receiving code line, the code works perfectly. Here is the code.
setTimeout(function () {
var response = xhr.response;
document.getElementById("bdy").innerHTML = response;
}, 50);
Thanks
Upvotes: 0