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.
Related
I have a working web page, complete with a JavaScript function that displays text messages based on the "non-successful" results, within the same page. Everything is working except this last step.
I need to send a JSON string to my server in a POST, and regardless of outcome, I need the user's browser to navigate to the page returned in the POST. (Just as if it were an ordinary link ( href ="" type of thing.) I am using the custom tag [OK_RESULT_URL] that my server replaces with the real URL just before the page is downloaded.
You see in my code below, that I set the URL to [OK_RESULT_URL] AND the window.location to [OK_RESULT_URL] as well, which seems wrong. That means I'm making two hits to [OK_RESULT_URL], one is a POST with a body (which is correct) and the other one a GET without a body (which is wrong).
I'm a total newbie to JavaScript, so I'm probably missing something obvious. It's as if instead of using xhr.Send() I want to say xhr.SendAndNaviateTo() ... or something like that.
Thanks for any help you can provide.
onApproval: function (response) {
showResult("Approved", JSON.stringify(response, null, ''\t''));
let xhr = new XMLHttpRequest();
let url = "[OK_RESULT_URL]";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200){
window.location = "[OK_RESULT_URL]"};
var data = JSON.stringify(response);
xhr.send(data);
}
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 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.
I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.
My quesion then is: Does anyone have any sample code that will do this?
Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4) { // Done loading?
if(this.status == 200) { // Everything okay?
// read content from this.responseXML or this.responseText
} else { // Error occurred; handle it
alert("Error " + this.status + ":\n" + this.statusText);
}
}
};
xmlhttp.send(null);
A couple of notes on this code:
You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found here.
You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
You may want to do things when earlier readyStates are received. This page documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.
Robert Walker did a great job of describing how to send the request. You can read more about Mozilla's xmlhttprequest here.
I would just add that the response would be found (using Robert's code) using
xmlhttp.responseText
(Edit - i didn't read closely enough, thanks Robert)
You didn't indicate exactly what the data was, although you mentioned wanting to parse links from the data. You could the xmlhttp.responseText as an xml document, parse out the links, and place it into a menulist or whatever you like.