简体   繁体   中英

Show alert after reloading page

I have tried this function but it displays the alert then refreshes the form. I want something that refreshes the page and then displays the alert . How can I do that?

 $(document).on('click', '#insert', function(){
   var address = $('#to_address').val();
    var amount  =  $('#amount').val();
    var this_email  =  $('#this_email').val();
    var this_bal  =  $('#this_bal').val();
   if(address != '' && amount != '' && this_email != '' && this_bal != '' )
   {
    $.ajax({
     url:"WithdrawChk.php",
     method:"POST",
     data:{address:address, amount:amount, this_email:this_email, this_bal:this_bal},
     success:function(data)
     {
      $('#alert_message').html('<div class="alert-success">'+data+'</div>');
     }
    });
    setInterval(function(){
     $('#alert_message').html('');
    }, 5000);
   }
   else
   {
    alert("All Fields are required");
   }
  });

You can do something like this

        success: function(data) {
          window.sessionStorage.setItem("successData" , JSON.stringify(data));
          window.location.reload();            
       }

$(document).ready(function(){
    if(window.sessionStorage.getItem("successData")){
      $('#alert_message').html('<div class="alert-success">' + JSON.parse(window.sessionStorage.getItem("successData")) + '</div>');             
}
})

Make sure to clear the session storage before the ajax call. And you can store only string values in the local or session storage so you have to stringify the json object to store it in session storage, and then if you want to use it, you have to parse that.

As per Rorys suggestion you can store the data in localStorage and check for if it exists on the jQuery page ready function.

 var localStorage = window.localStorage;

 $(function(){
        var data = localStorage.getItem("data");
        if(data !== null){
            $('#alert_message').html('<div class="alert-success">' + JSON.parse(data) + '</div>');
            localStorage.removeItem("data");
        }
 });


  success: function(data) {
      localStorage.setItem("data", JSON.stringify(data);
      window.location.reload();
  }

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