ViRaPa
ViRaPa

Reputation: 13

How to show success message and refresh the page together

I have JSP Servlet code which uses AJAX to process user data. In the success function of AJAX I want to show a success message to the user and I also want to clear all the fields in the form, so I reload the page. However when I reload the alert disappears. What is the solution for this?

$.ajax({
  url: '../Groups',
  data: {
    "mode": "create_assign",
    "name": name,
    "desc": desc,
    "status": status,
    "add": listadd
  },
  type: 'POST',
  success: function(response) {
    $.notify({
      message: "Created group successfully.",
    }, {
      type: "success"
    });
    location.reload();
  },
  error: function(jqXHR, textStatus, message) {
    $.notify({
      message: "System Error: Please try again or contact system admin.",
    }, {
      type: "danger"
    });
  },
  complete: function() {
    $('.overlay').hide();
  }
});

Upvotes: 0

Views: 1998

Answers (3)

Sulhan
Sulhan

Reputation: 116

Or instead of reloading the page, you could display the success message and then get the form inputs and clear them, which would look like something like this:

$('#yourForm').each(function(){
    this.reset();
});

Upvotes: 0

Arvind
Arvind

Reputation: 184

Its redundant, as mentioned by Chris, but have you considered using setTimeout()?

You could do this for example:

function successFunction(response) {
  $.notify({ message: "Created group successfully." }, { type: "success" });
  setTimeout(location.reload(), 4000); // time in milliseconds
}

and in your main ajax call add :

success: successFunction(response)

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Reloading the page after making an AJAX request is rather redundant. It makes the entire point of the AJAX request moot.

If all you want to do is clear the fields in the form after submission you could either do it manually:

success: function(response) {
  $.notify("Created group successfully.", "success");
  $('#yourForm input').val('');
},

Alternatively, you could just reset the form to its initial state:

success: function(response) {
  $.notify("Created group successfully.", "success");
  $('#yourForm').trigger('reset');
},

Note the above examples use the less verbose shorthand call to $.notify(), as can be seen in the documentation

Upvotes: 1

Related Questions