XMLHttpRequest JS Image loading - javascript

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.

Related

Alternatives to XMLHttpRequest when fetching upload progress

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).");
}

Will an ajax call finish even after a page redirect?

I am trying to create a temporary image url for a local image and send it to Google to do a Search by Image. I don't want the image url to be permanent so I want to delete it right after I use it. I have the code below:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(); // asynchronous call to server to delete the URL
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ xml.responseText; // the image url
}
}
xml.open("GET", "REST_ENDPOINT", true);
xml.send();
}
The function above calls the server, and when it finishes, will delete the url and redirect the page. The function "deleteImageURL()" is another ajax call done asynchronously. Currently, this loads the google page fine as the image URL is not done deleting the url by the time that the redirect happens.
My question is this: Will deleteImageURL() finish deleting the image URL even after the page redirects or will it stop (and thus, never delete the URL)?
EDIT: So I was thinking about what you guys were saying about race conditions and tried the following code instead:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(xml.responseText);
}
}
xml.open("GET", "REST_ENDPOINT"
+ id + "/public_url", true);
xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
var xml = new XMLHttpRequest();
xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
xml.send();
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ imageURL;
}
This code works every time that I run it. I think that there still may be a race condition, but it seems to be working fine so far.
Thanks again.
The "deleteImageURL()" will finish deleting the image URL even after the page redirects..
Refer : Should I wait for ajax to complete to redirect a page?
The server won't stop processing the request (initiated by deleteImageUrl), but you will not be able to handle a callback if the current page unloads in the browser before the operation is completed.
If deleteImageURL(); contains an async call you should do the redirect when the call is completed. Your code will work when the call is synchronious. We don't see the source of deleteImageURL(); and can be more concrete, but you should do the same thing as you've done for getImageURL().

XHttpRequest 2 page progress not working

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

Is it possible to track 404 answers from server by JS?

Sometimes clients requests resources that doesn't exists. We don't know why. Is it possible to track such events by JS (when server returns 404 for js, css, png) files?
To track error pages you will need to have the Google Analytics Tracking Code (GATC) added to your error page templates.Without the tracking code on the error pages you will not be able report on these pages or find their associated broken links.Please read more about GATC.I think tracking of such error is not possible by JS.If you found any then please let us know.
Thanks & Regards,
Mainak
You can, if you do an Ajax prefetch (jQuery is very handy for that). You just need to catch the click event on every link and do a synchronous ajax call. In the case of a 404 you can provide a proper error message, and if it works, just follow the link.
If the page is properly caught, your server shouldn't have extra work to do.
You could use something like this for images:
function preloadImages(data) {
var newImages = [];
for (var i = 0; i < data.length; i++)
{
try
{
newImages[i] = new Image();
newImages[i].src = data[i];
console.log(newImages[i].src);
newImages[i].onload = function() {
var src = this.src;
console.log("Succes loading image: " + src);
};
newImages[i].onerror = function() {
var src = this.src;
console.log("Error loading image: " + src);
};
}
catch (ex) {
console.log("Image Loading Error: " + ex);
}
}
}
var images = [
'http://cdn.sstatic.net/stackoverflow/img/sprites.png',
'unknown.jpg'
];
preloadImages(images);
Unfortunately, you still have to know links for all your images and you cant track js and css files with this.
So you definitely need ajax...
function urlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
and then you need function that will check every possible js, css and png link. Which is easy to make (assume that you want to track only 3 html elements: and ).
Since you are not trying to track images called as background-image inside css file, this is much more harder...

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.

Categories