D Aon
D Aon

Reputation: 143

Prevent ajax post when back button is pressed

When the form is posted(ajax), I am navigating to other page and while pressing the back button, the form is again posted.

Is there any way to stop ajax post while clicking on back button in browser ?

I have used the below code to stop previous request, but after this back and forward button are disabled in the browser.

window.onpopstate = function (e) {}; history.pushState({}, '');

NOTE: I am getting this issue only in chrome and safari.

Upvotes: 0

Views: 1037

Answers (1)

Parvez Rahaman
Parvez Rahaman

Reputation: 4387

As this answer suggest suppose you have this ajax request

var xhr = $.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston",
  success: function(msg) {
    alert("Data Saved: " + msg);
  }
});

window.onpopstate = function(e) {
  //kill the request
  xhr.abort()
};
history.pushState({}, '');

Upvotes: 1

Related Questions