Based on reading some documents from mozilla i just wanted to try out the html5 "xhr2" (so called) functionality. SO i used this code...
var oReq = new XMLHttpRequest();
function transferComplete(evt) {
alert("The transfer is complete.");
}
oReq.upload.addEventListener("load", transferComplete, false);
oReq.open('POST',"https://www.google.com",true);
I placed the above code in the head section of my page , but the page always loads but none of the events are fired..
Could someone please tell me what im doing wrong ....
Thanks guys
there's couple problems in your code.
you need to remove keyword upload before addEventLIstener
you need to call send() method on oReq object
cross-origin policy won't allow you to load https://www.google.com, but you still can load documents on the same domain
check this code:
var oReq = new XMLHttpRequest();
function transferComplete(evt) {
alert("The transfer is complete.");
}
oReq.addEventListener("load", transferComplete, false);
oReq.open('GET',"/index.html", true);
oReq.send();
try it on JSFiddle
Related
I've started a small project that I planned on just using PHP for, but I've ended up needing to integrate javascript with.
I was hoping someone could confirm if this is possible to do with javascript.
Basically I need to get the content from a specific URL, we'll call it:
http://example.com/api/API-DETAILS
That URL will respond with a number. If the number is over 0, then I want to simply run a PHP file, we'll call it:
http://website.com/file.php?data=test&more=example
If the number isn't above 0, nothing else needs to be done.
Is this something that could easily be done in Javascript?
Use XHR (XMLHttpRequest):
function reqListener () {
if (this.status==200)
{
if(this.responseText !== '0') {
location="http://website.com/file.php?data=test&more=example";
}
}
else
throw new Error(this.statusText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://example.com/api/API-DETAILS");
oReq.send();
I've been noodling with an XMLHttpRequest to update users on upload progress for large files in a web form:
function progressHandler(event) {
var percent = Math.round((event.loaded / event.total) * 100);
$('#loader').text( percent + '%' );
}
$("#Submit").click(function () {
var file = document.getElementById('fileupload').files[0];
var formData = new FormData(document.getElementById("new-job-form"));
ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
// we'll come back to this
}
}
ajax.open("POST", "#Url.Action("NewJob", "Home")");
ajax.send(formData);
});
And this works fine, up until the point the load completes.
My web application backend is written in .Net MVC and originally used this after the file upload was complete:
return RedirectToAction("FieldMapping", new { jobId = job.JobId });
This no longer works, because I've made the call asynchronous by invoking XMLHttpRequest.
The alternative is to return Json containing the target Url and redirect to that. This is a pain, and I'm having trouble getting it work properly. There are a few questions about this already on SO and the consensus is: don't do this. The whole point of Ajax is deal with partial responses, not whole-page redirects.
Which I understand, but I don't know of another way I can monitor the progress of a file upload and send it back to the user without using XMLHttpRequest. Is there another way to approach this, so I can just RedirectToAction after the request is complete?
I think you are looking for this: Using XMLHttpRequest
Progress events exist for both download and upload transfers. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:
var oReq = new XMLHttpRequest();
oReq.upload.addEventListener("progress", updateProgress);
oReq.upload.addEventListener("load", transferComplete);
oReq.upload.addEventListener("error", transferFailed);
oReq.upload.addEventListener("abort", transferCanceled);
oReq.open();
Why not do your "redirect" in the "load" event handler, which lets you know that the upload is finished? You could also use this:
One can also detect all three load-ending conditions (abort, load, or error) using the loadend event:
req.addEventListener("loadend", loadEnd);
function loadEnd(e) {
console.log("The transfer finished (although we don't know if it succeeded or not).");
}
I'm currently working on a project trying to update a page reading from an XML file on our intranet server. After doing some working I came up with the following code:
// IE7+
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
// IE6, IE5
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET", "VerifiedUrl+XML.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
if (xmlDoc.getElementsByTagName("CheckBox")[0].childNodes[0].nodeValue == "True"){
document.getElementById("PartToUpdate").innerHTML = xmlDoc.getElementsByTagName("TextBox")[0].childNodes[0].nodeValue;
}
Now I've tested this code on my localhost and it does in fact read from the correct file, displaying the updated information, but when I deploy it to the intranet, I get an "Invalid Argument" error. (The XML file itself has been deployed and is referencing correctly).
Edit: I've recently found the problem, in that the path I was referencing apparently couldn't find the file itself. So that brings up another question that someone might be able to shed light on:
//When referencing a file within the same folder, it works correctly.
xmlhttp.open("GET", "Sample.xml", false);
//However, if I include the full path, it doesn't read correctly. (Double slashes to escape correctly)
xmlhttp.open("GET", "\\\\Full\\Server\\Path\\Here\\Sample.xml", false);
Perhaps someone could shed some light on this?
should your path be something like this:
xmlhttp.open("GET","./Path/Here/books.xml", false); //for relative urls
xmlhttp.open("GET","http://localhost/Path/Here/books.xml", false); //for absolute urls
and if its a non-http synchronous request
var request = new XMLHttpRequest();
request.open('GET', 'file:///home/user/file.json', false);
its not similar to your system path.
The path here is wrong:
xmlhttp.open("GET", "\\\\Full\\Server\\Path\\Here\\Sample.xml", false);
You are using the wrong type of slashes for the internet, they would be correct on a file system. It needs to use a forward slash.
xmlhttp.open("GET", "//Full/Server/Path/Here/Sample.xml", false);
Have you checked the same-origin policy?
I want to implement the following things by using JavaScript:
using AJAX to get a page source;
put in some data into this page source;
show the changed page to users.
So it is possible? If so, how?
By the way, I cannot use server side technologies. And if JS is not suitable for it, what client technologies can be used in this case?
Assuming that the page you are wanting to get source from is on the same domain, you can get the page source like this:
if("XMLHttpRequest" in window){
xmlhttp=new XMLHttpRequest();
}
if("ActiveXObject" in window){
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open('GET', "URLofFileYouWantToGetTheSourceFrom", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
};
xmlhttp.send(null);
I want to create a website which loads a image via XMLHttpRequest(). (XMLHttpRequest because I want to represent the user a % progressbar)
My Code:
var req = new XMLHttpRequest();
req.addEventListener("progress", onUpdateProgress, false);
req.addEventListener("load", onTransferComplete, false);
req.addEventListener("error", onTransferFailed, false);
req.addEventListener("abort", onTransferFailed, false);
req.open("GET", "image.png", true);
req.send();
function onUpdateProgress(e) {
if (e.lengthComputable) {
var percent_complete = e.loaded/e.total;
if (Math.round(percent_complete*200)>=20) {
$("#progress").animate({
width: Math.round(percent_complete*100)
}, 0);
}
}
}
function onTransferFailed(e) {
alert("Something went wrong. Please try again.");
}
function onTransferComplete(e) {
//Problem
}
My problem is I donĀ“t know how to show the image which is now loaded. I hope anyone can help me :) Thanks ...
You can do this using DATA URIs, but it's hard to make that work in all current browsers.
If caching options are set correctly, you can better load it twice: first using your AJAX request, then, after the image has been cached by the browser, another time using the usual image functions. The second time your image will not be retrieved from the server again, but the browser will use the cached file and show the image almost instantly.