Ajax keeps site on the Loading - javascript

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

Related

How can I stop caching when using AJAX to read a file?

I'm currently building a website that uses AJAX to dynamically update sections of the page without the need to refresh, however, when I change aspects of the file that AJAX reads the website sometimes takes minutes to update even though the file is read about once per second. Whilst looking for the issue I found that I can turn caching off by using the developer tools and this then allowed the website to update at the appropriate speed.
Here's the code I am using:
var path = "Path of the json file i am reading"
var state;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
state = JSON.parse(this.responseText);
}
};
xhttp.open("GET", path, true);
xhttp.send();
I've been looking for a while now and the only advice I can see about what to do about the cache is to use the developer tools to turn it off. Is there any way I can implement some code to automatically tell the browser to not cache the file being read?

XMLHttpRequest to the MongoDB simple rest interface

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
}
}

cannot manipulate response from xmlHttpRequest 2

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.

Ajax Function Only Working Part of the Time

I am using the following Ajax function format:
var xmlhttp;
function addAddress(str)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
var addAddress = "add";
xmlhttp.open("POST", "sys.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&addAddress=" + addAddress;
xmlhttp.send(queryString);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (windows.ActiveXObject)
{
return new ActiveXObject("Micorsoft.XMLHTTP");
}
return null;
}
Up until now, all of my Ajax functions, like the one above, have been running fine. However, now the function will work only sometimes. Now, sometimes I will have to click the onclick event a couple times to execute the function or the function will just hang, and then after about 4 minutes it will execute.
I tested parts of the function and found that the issue lies some where at the:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.status);
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
When the function works, I can alert(xmlhttp.status) and get 200. However, when it's not working, the alert box doesn't even trigger. In fact, nothing happens, not even an error.
Could this be a server issue? I am kind of thinking my website got hacked, but I cannot find any issues accept that the Ajax functions are not executing properly.
Lastly, I do not get this problem on my localhost, it's only happening on the live website.
Any help will be greatly appreciated.
Thanks
First just confirm that the addAddress function is actually being called when you click the button or control that should trigger it.
Just a simple alert in the first line like this would work:
function addAddress(str)
{
alert('addAddress has been called!')
....
}
If you don't get the alert, make sure there isn't a javascript error on the page that is preventing the function from running. In firefox you press CTRL+SHIFT+J to see the error console for example.
If that part is working, trying putting the URL for the ajax request directly into your browser and diagnose it that way.
Looks like you are requesting this url with ajax:
sys.php&addAddress= (address goes here)
Check that the page will load directly in your browser. If not, the problem is not the ajax request, but something with the sys.php page itself - which you can then drill down on.
Hope that helps!
This wasn't the answer I was expecting, but I ended up having my web host (GoDaddy) change servers, and that resolved the problem. For almost a year, I was running IIS7 with PHP. Since I had never run into any problems, I just continued using that server. After the Ajax latency issue and not being able to figure out a solution, I figured I would just switch over to Apache. After the change, everything started running smoothly again.
I am thinking maybe there was a software update that I was not notified about. Or, maybe my website was getting hit with a DDoS, which was decreasing the performance of my Ajax requests. Lastly, maybe someone got into IIS and changed a setting. I don't know, all I know is that the minute the server was changed over to Apache was when the website started running normally again.
Thanks for everyone's suggestions.

how to load all elements on my page with javascript?

I have a dynamic page with different elements in each generates, and I want to load all of their lines to an alert for example or a page with JavaScript. Is this possible?
For example, if I had this line to my page:
<marquee> This is for test </marquee>
I want to show all of it to an alert or a page, somethings like that :
Pseudo-code:
<script>
alert(getAllData) | write(getAllData)
</script>
Output: (in alert)
<marquee> This is for test </marquee>
You can use Ajax. Here's an example that alerts the contents of the page test.aspx, for example:
var rq;
// Initialize the request:
if(window.XMLHttpRequest) {
rq = new XMLHttpRequest(); // Standards-compliant way, compatible with every browser except IE6 and under
} else {
rq = new ActiveXObject('Msxml2.XMLHTTP'); // IE6-compatible.
}
// Open the request:
rq.open('GET', 'test.aspx', true); // GET is the method (you're probably familiar with this), test.aspx is the URL, and true means send asynchronously.
// Set up the state-change handler:
rq.onreadystatechange = function() {
if(rq.readyState === 4) { // Request complete
alert(rq.responseText); // The response is in the responseText property.
}
};
// Finally, send the request:
rq.send(null);
For more information, Google "Ajax." There are plenty of good tutorials.

Categories