简体   繁体   中英

How to reload an image using ajax

Here is my captcha.php script: (it creates an image)

// creating a image in this script and set its value on the session

Also I have a <img> in the contact_us.php file for showing that captcha image:

<img src="http://localhost/captcha.php" class="captcha_pic" alt="Captcha">

Also I have an ajax code for submiting that form in the contact_us.js (this file is atteched to contact_us.php) :

$("#f_contact_form").on("submit", function (e) {
   e.preventDefault(e);
   $.ajax({
      url:  $("#f_contact_form").attr("action"),
      type: 'POST',
      data: $("#f_contact_form").serialize(),
      dataType : 'JSON',
      success: function (contact) {
        $(".contact_message").html(contact.message);

        // here I need to reload that image url for changing the captcha image

      }
   });
});

It should be noted that when I change the url of that image using [inspect element] (in the static) and then I write the correct name, the image will be changed. for example I replace the current image url with src=".../captcha.ph" and then I write the correct name src=".../captcha.php" , then the page will be changed (exactly what I want).

Now there is any solution for reloading captcha image?

You need to reload your image with a unique query string attached to it, in order to prevent your browser from caching the image. The easiest way is to just append the current time. Since you are already using jQuery, here's one way you can do it.

var unique = $.now();
$('.captcha_pic').attr('src', 'http://localhost/captcha.php?' + unique); 

However, some people may recommend against this solution as it can fill up your cache. Although the alternative will require that you send cache control headers.

There's a lot of solution for there. Here are some of your options.

  1. Remove your images , then create a new one.

     $("#images").remove(); $("div").html("<img src='http://localhost/captcha.php' class='captcha_pic' alt='Captcha'>")
  2. Using unique to avoid cache.

     $("#f_contact_form").on("submit", function (e) { e.preventDefault(e); $.ajax({ url: $("#f_contact_form").attr("action"), type: 'POST', data: $("#f_contact_form").serialize(), dataType : 'JSON', success: function (contact) { $(".contact_message").html(contact.message); $('.captcha_pic').attr('src', 'http://localhost/captcha.php?' + new Date().getTime()); } }); });

$.now() has been deprecated in jQuery 3.3 . Correct way based on accepted answer:

var unique = Date.now();
$('.captcha_pic').attr('src', 'http://localhost/captcha.php?' + unique); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM