I have a button that user clicks and download from a PHP page, since the processing is a little bit long i want to display a text that shows the user that their request is processing, i found the onreadystatechange Property can be accessed so maybe I can use it for the task.
ready StateHolds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
My code is below, i able the get the readyState == 4 but cannot get the readyState == 3, any advice would be great!
<button type="submit" class="btn btn-primary" id="weekDL">
<i class="fa fa-download"></i>
Download
</button>
<p id="please">Generating report, please wait..</p>
$('#weekDL').on('click',function(){
$(this).hide();
$('#please').show();
var data = $("#week option:selected").text();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 3) {
$('#please').text('Request recieved..');
} else if (this.readyState == 4 && this.status == 200) {
window.location = "PHPexcel/download.php?week=" + data;
this.responseText;
$('#please').hide();
$('#weekDL').show();
}
};
xhttp.open("GET", "PHPexcel/download.php?week=" + data, true);
xhttp.send();
});
});
Your code is working fine. The issue is because state 3 is only around for a couple of milliseconds before state 4 occurs (depending on the size of the response), therefore your UI update is almost imperceptible.
You can verify this by placing console.log('state: ' + this.readyState); within the onchangereadystate handler. You will then see the output of all 4 states in the console.
Working example
This is of course assuming that the AJAX request is returning a valid response. If there is an error in the request then you would only see states 1 and 4. However in that case the problem is with the logic in the request, not your JS.
Related
In my below code, I tried to stimulate how each statement gets executed line by line while processing synchronous ajax requests. I have sent two ajax requests synchronously introducing a delay between two requests. The problem is i'm getting "Request 1" in console but not getting the response text in my dom. After delay ends, and my second request ends, the first responseText is displayed and then second responseText is displayed in my dom.
Why My first ajax response text getting late to update in my dom, even though I got a response from server-side before the delay gets start?
index.html
-----------
<!DOCTYPE html>
<html>
<body>
<!--Calls the function synchronously(async=0/false) -->
<button type="button" onclick="loadDoc('ajax_info.txt')">Synchronous Operations</button>
<p id="result1"></p>
<p id="result2"></p>
</body>
<script type="text/javascript">
function loadDoc(url) {
console.log("Entered ");
ajax(1,url,"result1");
for(i=0;i<1000000000;i++){}
ajax(2,url,"result2");
console.log("Exit");
}
function ajax(requestNo, url, div) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(div).innerHTML = this.responseText;
console.log("Request " + requestNo);
}
};
xhttp.open("get", url, 0);
xhttp.send();
}
</script>
</html>
ajax_info.txt
--------------
This is the content from a txt file.
I think there is something wrong with your response. I used a publicly available fake endpoint to reproduce this, but it works as expected:
https://jsbin.com/kojowaneda/1/edit?html,js,console,output
The only diff between this code and yours, is the parameter of the function call:
<button type="button" onclick="loadDoc('https://jsonplaceholder.typicode.com/todos/1')">Synchronous Operations</button>
Also, you should use setTimeout for a timeout instead of a for loop.
I am trying to get data form a website about institution using XMLHttpRequest but rather than data I am getting error page please help
My code:-
var url = '[https://tsecet.nic.in/institute_details.aspx?iCode=JNTH][3]';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.write( this.responseText);
}
}
xhttp.open("GET", url , true);
xhttp.send();
Target Web Page Address:-
https://tsecet.nic.in/institute_details.aspx?iCode=JNTH
If I try to open
https://tsecet.nic.in/Default.aspx>>then click on >>
institute profile >> then click on>>JNTH
Then I am able to get data in browser Else I am redirected to an error page
Please help me...
Note
I am trying to get this data from a different website and a different
domain This website is scripted in aspx
The AJAX request you're trying to run can't do that, as the pages have the X-XSS-Protection: 1 header, blocking such requests. It looks as if they allow the internals URIs to launch only within a "frame" set by the homepage. Unfortunately, I can't tell for sure. In short, you are going to need another approach.
I ve been trying to figure out how to make this work.
var request;
if(window.XMLHttpRequest){
request= new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var handleStateChange = function () {
switch (request.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
break;
default: alert("error");
}
}
/*request.onreadystatechange=handleStateChange;*/
request.onreadystatechange = function(){
if((request.status === 200) && (request.readyState === 4)){
console.log(request);
document.writeln(request.responseText);
}
}
request.open('GET','data.txt');
request.send();
I found similar problems here in stackoverflow, but yet I havent figured out why its behaving this way (Im new to Ajax).
So the problem is, when I have request.open('GET','data.txt'); its causing the page to stay on loading mode and the console.log doesnt show anything.
I google around and found in stackoverflow this solution request.onreadystatechange=handleStateChange;
which seems to be fixing the problem. unfortunately it overrides the request.onreadystatechange = function(){}. Console works and the data.txt content wont show on the web.
If I comment it out, the content shows on the web, but the page keeps loading again.
I figured that its something to do with readyState and that by the time it reaches 4 the responseText is empty. But how can I get it to show the content and the console.log?
Thank you in advance for your time :)
but with it console works without showing any results on the website
As per your comment, I can suggest you that you are using a wrong method. There is no writeln method in javascript, instead you are suggested to use .write()(although not recommended).
change to this:
document.write(request.responseText);
or better:
document.body.innerHTML = request.responseText; // use this response contains html tags
or:
document.body.textContent = request.responseText; // use this response is just text
I am a beginner in both Ajax and MongoDB. I was hoping to visualize some of the data in my MongoDB using a web browser (which, for the moment, is running on the same host). For this, I thought it might be possible to get the data using XMLHttpRequests. I am running MongoDB with the --rest option and I checked that when I load hxxp://localhost:28017/test_db/ss_test/
on Firefox, I get the proper reply (a JSON document with the data in the ss_test collection of the test_db database). So far, so good.
I then wrote the following JavaScript function which I connected to the "onclick" of a button:
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
So, when I load the html file on Firefox, open the console and click on my button, I see that the http request is indeed made, the status code is "HTTP/1.0 200 OK" and a response with Content-Length: 219257 is delivered, which looks great. However, the XMLHttpRequest object does not report the status=200. The alerts that pop up report a constant status of 0 as the readyState progressively becomes 1, 2 and 4 and my if statement is never true.
Could anyone please tell me what I am doing wrong? In the beginning I thought it was because my html was loaded on the browser by the file protocol or that I was seeing some same-origin policy related issue, but then I put the html file on a web server on localhost and loaded it from there and nothing changed. Thank you very much for any replies!
you need to create a function to handle the request.
http://www.ibm.com/developerworks/web/library/wa-ajaxintro2/
http://www.ibm.com/developerworks/library/wa-ajaxintro3/
function makeRequest()
{
var myrequest = new XMLHttpRequest();
myrequest.onreadystatechange = create_this_function()
{
}
myrequest.open("GET", "http://localhost:28017/test_db/ss_test/", true);
myrequest.send();
}
#
function create_this_function()
{
alert("status=" + myrequest.status + " readyState=" + myrequest.readyState)
if (myrequest.status == 200 && myrequest.readyState == 4)
{
// ...do something with the response
}
}
I'm using XHR 2 to upload/save files.
According to the response of the server I want to perform an action. For example if the responce is "Saved" I want to hide a div or if the response is "Not Saved" I want to show another div etc...
I implemented what appears to be a simple code that should be working , but is not
Here is the snippet of the XHR
//initialize
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php');
xhr.responseType="text";
xhr.onload = function() {
//if all ok....
if (xhr.status === 200)
{
//update html5 progress bar
progress.value = progress.innerHTML = 100;
//get the respnse
var data=xhr.response;
//convert it to sting - kind of overkill, I know, but I'm stack
var data2=data.toString();
//alert it -- works
alert('data2 '+data2);
//now, do something, according to the response -- NOT working, never alert anything
if (data2=="Not Saved"){alert('Ooops, not saved');}
if(data2=="Saved"){alert('It's all good');}
if(data2=="File too big"){alert('hey, you are watching Jake and Amir');}
document.getElementById('imagesaved').innerHTML=data;
}
//refers to if (xhr.status === 200)
else {document.getElementById("imagesaved").innerHTML="Connect to server failed";}
What is wrong here? This should be working right? Any suggestions?
Thanks
EDIT
I put the alerts for testing. What I actually want to do is call some functions.
If I put
if (data2=="Not Saved"){functionOne();}
if(data2=="Saved"){functionTwo();}
if(data2=="File too big"){functionThree();}
the functions never get called
if I put
if (data2!="Not Saved"){functionOne();}
if(data2!="Saved"){functionTwo();}
if(data2!="File too big"){functionThree();}
ALL the functions are called!!!
I still dont get it...Maybe its something with the response? Or the onload function?
Thanks again
What I finally did is make the server response with numbers, not text. So encoding does not matter any more...
This is the code
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status == 200)
{
var data=xhr.response;
if(data==1)
//say to the user is saved
{document.getElementById('imagesaved').innerHTML="Saved";}
//say to the user, there was an error
else{document.getElementById('imagesaved').innerHTML="Error";}
}
//say to the user that connection to the server failed
else {document.getElementById("imagesaved").innerHTML="Cannot connect";}
};
xhr.open('POST', 'upload.php');
xhr.send(formData);
This is a workaround. I dont know if its the right way to solve this problem , technically. I decided to post it anyway, to help others to quickly solve similar problems. If anyboy else has a better way to suggest , please do.
In this line : if(data2=="Saved"){alert('It's all good');}, you have to escape " ' ".
So convert it to : if(data2=="Saved"){alert('It\'s all good');}
Are you sure that the response of your ajax is text/plain ?
Look on the console (ctrl+shift+i on chrome, F12 on firefox), on net or network tab.
Look on console tab if you got some javascript errors too.