In the captcha.php file, I create a gif image using the GD library and display it in a form to send a comment to the article.

<img class ="captcha_img" src="captcha.php" /> 

How can I update an image using ajax request?

  • 2
    It seems to me that AJAX is not needed here. Just update the image src attribute. - Stepan Kasyanenko

3 answers 3

 let captchaUpdate = document.querySelector(".captcha_update"), captchaImg = document.querySelector(".captcha_img"); captchaUpdate.addEventListener('click', () => captchaImg.src = "captcha.php?r=" + Math.random()); /* Вывод результата в консоль */ captchaUpdate.addEventListener('click', () => console.log(captchaImg.src)); 
 <img class ="captcha_img" src="captcha.php" /> <button class="captcha_update">Обновить</button> 

    With normal settings, nginx / apache will work and such

     <img class ="captcha_img" src="captcha.php" onclick="this.src = this.src"/> 

    When you click on the image, the captcha will reboot.

    • It will work only if the caching headers on the server are correctly configured. - Qwertiy

    I found the following solution ...

     var unique = $.now(); $('.captcha_img').attr('src', 'captcha.php?' + unique); // перезагрузить капчу 
    • And how does cleaning of your form relate to the question? - Qwertiy
    • Not applicable. Removed. - Oleg
    • one
      By the way, in this case it is better to use prop , not attr . - Qwertiy