Javascript: Verify External Url Of An Image
Solution 1:
Your code in this post is not a correct implementation of the function I gave you in the previous post and will not work for a number of reasons. You cannot return true/false from the onload, onerror handlers. Those are asychronous events and your vrfyImgURL
function has already returned.
You really HAVE to use the code I put in that previous post. It works. Just use it. Don't modify it. You pass in a callback and that callback gets called with the validation check results. You have to use asynchronous programming to use this where the callback gets called with the result. You can't use straight sequential programming like you are trying to do. It is your modifications to my code that have made it stop working.
You can see the code I gave you previously work here:http://jsfiddle.net/jfriend00/qKtra/ and in the example, it's working with images from a variety of domains. It is not sensitive to the domain of the image and <img>
tags are not restricted by domain.
To hook it up to your form submit, you can do this:
<formaction="http://www.example.com/current_page"enctype='multipart/form-data'method="post"onsubmit="return formSubmit();"name="submitIMGurl"><inputtype="text"value="http://"name="img_url" /><inputtype="submit"value="Submit" /></form><scripttype="text/javascript">functionformSubmit() {
var url = document.forms["submitIMGurl"].elements["img_url"].value;
if (!checkURL(url)) {
alert("It looks like the url that you had provided is not valid! Please only submit correct image file. We only support these extensions:- jpeg, jpg, gif, png.");
return(false);
}
testImage(url, function(testURL, result) {
if (result == "success") {
// you can submit the form nowdocument.forms["submitIMGurl"].submit();
} elseif (result == "error") {
alert("The image URL does not point to an image or the correct type of image.");
} else {
alert("The image URL was not reachable. Check that the URL is correct.");
}
});
return(false); // can't submit the form yet, it will get sumbitted in the callback
}
functioncheckURL(url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
functiontestImage(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = newImage();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
</script>
If this were my interface, I would disable the form and put up a note that the image URL is being checked starting when testImage is called and ending when the callback is called.
Post a Comment for "Javascript: Verify External Url Of An Image"