JavaScript 404 code detection

I need to be able to detect missing image in JavaScript.

PHP on the server cannot be used because href is computed using JavaScript. Script that works when a file exists:

Data_ID = _DataRow.getDataItem()["Data_ID"];// Picks up the ID of the data _HitJPG = document.getElementById("HitJPG"); JPGFileName = _DataRow.getDataItem()["JPGFileName"]; directory = JPGFileName.slice(0, 10); directory = directory.replace(/-/g, "/"); _HitJPG.innerHTML = "<a href=http://77.88.99.54/data/" + directory + "/" + JPGFileName + " ><h3>JPG File for this Data </h3>" + JPGFileName + "</a>"; 

How can I determine the HTTP 404 code before setting "InnerHTML" to the Div?

0
source share
4 answers

You can use the onload and onerror to determine if the image is loaded.

 var Data_ID = _DataRow.getDataItem()["Data_ID"]; var _HitJPG = document.getElementById("HitJPG"); var JPGFileName = _SETIDataRow.getDataItem()["JPGFileName"];//"2014-04-29T13-36-27.JPG" var directory = JPGFileName.slice(0, 10); directory = directory.replace(/-/g, "/"); var image = new Image(); image.onerror = function() { // fail - image not available } image.onload = function() { // success - image available _HitJPG.innerHTML = "<a href=http://77.88.99.54/data/" + directory + "/" + JPGFileName + " ><h3>JPG File for this Data </h3>" + JPGFileName + "</a>"; } image.src = "http://77.88.99.54/data/" + directory + "/" + JPGFileName 
+3
source

You can try this using the ajax call as mentioned above. Let me give you a code snippet:

 $.ajax({ url: '<image file name>', // your file name success: function(data){ alert('exists'); }, error: function(data){ alert('does not exist'); }, }) 

The above code has already been specified in stackoverflow for other javascript related issues. You can check this also for clarification.

Check if javascript file exists

+1
source

You can use ajax

 var jqxhr = $.ajax( "your iamge url" ) .done(function() { alert( "success" ); }) .fail(function( jqXHR, textStatus ) { alert( "Request failed: " + textStatus ); }) .always(function() { alert( "complete" ); }); 

Link http://api.jquery.com/jquery.ajax/

0
source

You can do this with an ajax request, when you get a response from the server, check the response status , example javascript / jQuery >:

 function fileExists(urlToCheck){ var fileFound = true; $.ajax({ url: urlToCheck, type: "GET", success: function(data, textStatus, xhr) { console.log(xhr.status); if(xhr.status == 404) fileFound= false; }, complete: function(xhr, textStatus) { console.log(xhr.status); if(xhr.status == 404) fileFound= false; } }); return fileFound; } 

I think that this function can be improved much more, given the different HTTP response codes, the codes differ from 404, but this does not mean that the file exists on the server.

0
source

Source: https://habr.com/ru/post/956013/


All Articles