Receive text and picture from server in javascript - javascript

I need to refresh an img tag every second. so I wrote a little bit of code that changes src attribute of img tag and it loads the picture from image.php.
All good.
Sometimes the image.php doesn't have a picture, or sth went wrong in image.php. I need image.php to send a message along with the picture to determine validity of the picture, or tell me the error number.
so I need a php code that puts a text and a picture in it's output.
Right now I use
//code
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
and image.php acts like a .jpg file and I can use it in src attribute of img tag. But I need a way to find out if image.php is outputing a valid image and not a php error.
js code:
var newImage = new Image();
var count = 0;
function updateImage()
{
if(newImage.complete) {
document.getElementById("myimg").src = newImage.src;
newImage = new Image();
newImage.src = "socket.php?message=0&image" + count++ + ".jpg";
}
}

JavaScript-wise, you can find out about image failing to load via error event (jsfiddle).
Perhaps, you could request the same URL via Ajax if the image fails to load, to obtain the error message. Unless you'd want to encode error messages as images too (and decode them client-side), of course, which may, or may not be a good idea.

First method:
Using onerror property of the img element:
<img src="image.gif" onerror="alert('The image could not be loaded.')">
Source
You can use function as value of onerror property and use this function in java script. Example is below.
HTML:
<img src="image.gif" onerror="handleError();">
JS:
function handleError() {
// do something
}
Another way is to set onerror handler to instance of Image class:
var image = new Image();
img.src = /* url to the imgage */;
image.onload = function() {
// assign img.src to to src property of the `img` element
}
image.onerror = function() {
// do actions on error
}
Note:
2nd way is the way how to use new Image() correctly.

I would use Ajax for such a task, and send back the image path and any other added information from the server.
The Ajax response can be easily read by the client.

Related

How to use a html file as a source of image file in <img src=""> tag

I'm trying to use an html file as a source of an image file in <img src=""> tag to avoid mixed-content warning over https while using an http image.
Example:
index.html:
<img src="./image.html" >
image.html:
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
document.write(dataURL);
};
img.src = url;
}
getBase64FromImageUrl("http://www.w3schools.com/css/trolltunga.jpg");
<meta http-equiv="Content-type" content="image/png"/>
<!--
I do not want to add any child tags to the body in order to display image from this base64 data. i just want to display using the content headers.
-->
and I'm trying to use the image data that I dump into the html file using javascript now when I tried to open the Html file and I see a string that represents an encoded URL containing the grabbed graphical data but not the actual image as the headers are not set, even though I tried setting the content headers using meta tag in html file, nothing helped. I tried setting the content headers using .httaccess file but no use.
I know it is possible to use any server side script as the content headers that we set are sent from the server along with the response to the http request.
example:
image.php
<?php
header("Content-Type: image/png");
readfile("www.example.com/img.png");
?>
index.html
<img src="./image.php" >
I'm able to do this with php but I actually want to use html and javascript.
The main Idea is to be able to use http images over https without getting a mixed content warning.
So you might be better off dealing with an XHR and the FileReader API, like below:
var b64xhr = new XMLHttpRequest();
b64xhr.open( "GET", url );
b64xhr.responseType = "blob";
b64xhr.onload = function (){
if (b64xhr.status===200){
reader.readAsDataURL( b64xhr.response );
}
else if (b64xhr.status===404){
// error
}
};
var reader = new FileReader();
reader.onloadend = function () {
console.log (reader.result );
};
b64xhr.send();
This doesn't involve any sort of hack, but does have limited compatibility

Changing image extension with javascript/jquery only?

I'm making a simple slider to show off artwork for a friend of mine. I'm really only familiar with javascript/jquery, so I'm not 100% comfortable using something else right now.
Since my friend doesn't have any programming knowledge, I'm trying to keep this really simple for her to update (i.e., automating creating new images whenever she adds a new one to the folder). She will upload images to a folder and will have to number them (i.e., 1.jpg, 2.jpg). My javascript uses a for loop to loop through numbers (she will have to update the loop whenever she adds a new image) and insert them into the file name. HOWEVER this limits her to only uploading one type of file. Is there someway to change the extension only using javascript?
This is what I have so far:
function callImages(){
//create the image div
$('.artslider').append('<div class="image"></div>');
//create the files array
var files = [];
//start the loop, starting position will have to be updated as images are added
for (i=8;i>=0;i--){
//create the img src for a jpg img
var imgJPG = 'arts/'+i+'.jpg';
//find the natural width of the image after it loads to see if it actually exists
var imgWidth = $('imgJPG').load().naturalWidth;
//if the width is undefined, replace the jpg extension with gif
if (imgWidth===undefined){
var imgGIF = imgJPG.replace('jpg', 'gif');
files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
//otherwise keep the jpg extension
else {
files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}
//then add the images to the img div
$('.image').append(files[i]);
}
};
The problem with this if/else is that it will only create a gif image. If you switch the order, it will only create a jpg image.
edit: here's what this code produces: https://googledrive.com/host/0B1lNgklCWTGwV1N5cWNlNUJqMzg/index.html
The problem is with this bit of code:
var imgJPG = 'arts/'+i+'.jpg';
var imgWidth = $('imgJPG').load().naturalWidth;
imgWidth will always be undefined.
Firstly you are passing in the string 'imgJPG' instead of the parameter imgJPG. Secondly I think you have misunderstood jQuery selectors, this is used for selecting HTML elements, inputting a file path into here will not achieve anything. Thirdly I think you have misunderstood the load function, this is used for loading data from the server into a HTML element.
I would suggest using a function like below to check if the image exists:
function urlExists(url) {
var http = jQuery.ajax({
type:"HEAD",
url: url,
async: false
});
return http.status == 200;
}
Then in your code:
if (!urlExists(imgJPG)){
var imgGIF = imgJPG.replace('jpg', 'gif');
files[i] = '<img src="'+imgGIF+'" class="artsliderimg"/>';
}
else {
files[i] = '<img src="'+imgJPG+'" class="artsliderimg"/>';
}

Determine through javascript if another URL exists

I am working with a servlet which serves up an image. However, it takes about 30 seconds for this to be generated. When complete, it appears on an OpenLayers interactive map.
I am trying to figure out a way for the user, who is at www.test.com to get confirmation the image is being processed or is complete, which is located at www.test2.com. If I open test2.com, I can see that the page is trying to load. When complete, the image also appears on my map on test.com.
However, I can't figure out how to test if this image exists or not. I am looking for something probably like
if(image exists at http://test2.com) {alert("request is done");
or possibly
if(http://test2.com is loading) {doing something);
I just don't want the user sitting by if the request fails. If it fails, the url will complete its load - however, no image will appear. Any guidance will be very appreciated! Thanks!
Kyle
If it is a different server, JavaScript will not be able to make any type of Ajax request to that server to see if it exists. You would have to have a proxy on the local domain which could make a head request to the second domain.
If you are waiting until the image is loaded to work with it, you can always do an image preloader, but that will take the full time for the image to render before the onload event fires.
var img = new Image();
img.src = theUrl;
img.onload = function() {
nextStep(this);
};
img.onerror = function() {
imgLoadingError(this);
};
IF you have control over the other server, you could put a small image on that server and do something like this: (Untested code, typed in directly)
var img = new Image();
// Note the order of these two statements
img.onload = function()("The image loaded! Server must be up");
img.src = "http://example2.com/myflag.png";

Load image... when time is eating up

here is a sameple code, I would like to know when the browser is REALLY loading image
when you assign an image path to a array like that
imageNames[0] = 'image1.jpg';
or when you make
myImage = new Image();
myImage.src = imageNames[0];
i have put some timer.. but did not get concluant result ! HELP
You would look at the load event. Attach it with the ancient onload or addEventListener()/attachEvent() depending on your browser support requirements.
myImage = new Image;
myImage.onload = function() {
alert('Image loaded');
}
myImage.src = imageNames[0];
jsFiddle.
You could also check if the image is already loaded by checking the complete property.
The key thing to note is that just because a human being can see that something could be a resource identifier / locator, the computer cannot.
When you assign a string to a point in an array:
imageNames[0] = 'image1.jpg';
the fact that 'image1.jpg' is a licit path to an image on your.host.net is not something the browser can determine on its own - the browser cannot recognize that the string 'image1.jpg' is a resource representation rather than a resource itself.
Once you set a DOM image's src property to be the string 'image1.jpg' the browser can recognize the string should be treated as a resource identifier (because the DOM element you created is an image, and the image's src property is supposed to be a URI pointing at an image resource which can be accessed and downloaded) and the browser will try and acquire that resource through means of its own.
The browser downloads the image when you assign a URL to the src attribute of an img element. Try this in the console of your browser and watch the Network tab:
var img = document.createElement('img');
img.src = 'foo';
You'll see network activity as soon as that second line executes.
It most certainly does nothing for imageNames[0] = 'image1.jpg'; since a string in an array could be anything, there's no way the browser has any idea this is supposed to be the URL of an image.

Validate an image path in javascript

I have an image like: img src="" class='listPartialLoader' alt='loading'
I am assigning the 'src' value with data from an ajax call. Some times if the image is not found I want to add a default image path like"Images/default.jpg". But how can I check whether the image is exist or not using javascript? (Basically I want if the image is not found add a default image)
You should be able to check if the image exists with the onerror and onload events.
var myImg = new Image;
myImg.src = 'path/to/image';
myImg.onerror = function(){
console.log("Error!");
}
myImg.onload = function(){
console.log('Loaded!');
}
While you are retrieving the value for src property during the ajax call to the server, why not check if the file exists?
string src = GetSrc(); //whatever you need to do
if(System.IO.File.Exists(HttpContext.Current.Server.MapPath(src)))
{
return src;
}
else
{
return "path/default.jpg");
}
if the image is in the same domain of your script just take the image path (before assign it to image element) and make a simple HEAD ajax request to that path (eg. "images/default.jpg) . If server status is 304 or 200, the image exists

Categories