简体   繁体   中英

jQuery Ajax Response works only once until page refresh

This is simple subscriber form submit with jQuery Ajax, everything is working fine but alert response show only one time until page refresh.

Here is my view code:

$(document).ready(function () {
  $("#ssubmit").click(function (e) {
    e.preventDefault();
  
    let subscriber = $("#subscriber").val()
    subscriberdata = {subscriber: subscriber,}
  
    $.ajax({
      type: "POST",
      url: "form-process.php",
      data: JSON.stringify(subscriberdata),
      success: function (response) {
        subscribersucess = "<div class='alert alert-success text-center mt-3'>" + response + "</div>";
        $("#alerts").html(subscribersucess);
  
        setTimeout(function(){
          $('#alerts').fadeOut("slow");
        },5000)
  
        $("#subscriberform")[0].reset();
      }
    });
  
  })
});

How can I fix this issue?

This is happening because you are using fadeout function. Once fadeout happens display becomes none. And it will only works when you refresh the page.

You can use below code

let subscriber = $("#subscriber").val()

subscriberdata = {subscriber: subscriber,}

$.ajax({
  type: "POST",
  url: "form-process.php",
  data: JSON.stringify(subscriberdata),
  success: function (response) {

    subscribersucess = "<div class='alert alert-success text-center mt-3'>" + response + "</div>";
    $('#alerts').show().html();
                $("#alerts").html(subscribersucess);    
                    $('#alerts').delay(5000).fadeOut(); 
    


    $("#subscriberform")[0].reset();

  }

});

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