Jquery equivalent php file_exists ()?

In the code snippet below, from my jQuery setup, I need to check if the image file really exists, and if not, I would like to replace the default image. Currently, if the file does not exist, I just get a broken swatch ...

$('#myTheme').change ( function() { var myImage = $('#myTheme :selected').text(); $('.selectedImage img').attr('src','../wp-content/themes/myTheme/styles/'+myImage+'/screenshot.jpg'); //if screenshot.jpg does not exist, use "../../default.jpg" instead } ); 
+3
jquery
source share
3 answers

It looks like you need access to the HTTP response headers. Here is a snippet of code that I found on the Internet.

Source: http://www.vfstech.com/?cat=1

 $(document).ready(function() { var ajaxSubmitOptions = { // the normal success callback is not used // success: function (responseText) { // ... // } , complete: function (xhrObj, status) { if(status == "error") { // 500 server error? alert("There was an error processing this request."); } else { if (xhrObj.getResponseHeader("X-My-Custom-Header") != "") { alert("Intercepted special HTTP header..."); alert(xhrObj.getResponseHeader("X-My-Custom-Header")); } else { // call the function you normally would have used in the "success" callback: this._success(xhrObj.responseText); } } } , _success: function (responseText) { alert("Normal success callback..."); alert(responseText); } }; $('#myForm').ajaxForm(ajaxSubmitOptions); }) 
+1
source share

Since Javascript in the browser does not deal with files at all, you cannot check if the file exists. You can attach an error event , although it should fire if the image cannot be loaded. Note that you must do this before setting the src attribute to make sure you catch the event in a timely manner.

0
source share

Here I want to share one useful link for this requirement.

http://phpjs.org/functions/file_exists/

it is a javascript function that takes url as an argument and returns true if the file exists.

0
source share

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


All Articles