Prevent Form Redirect or Refresh on Submit

prevent form submit from redirecting/refreshing using javascript

The answer was (thanks to Ulysses for part fo the answer):

<form id="editForm" name="editForm" onsubmit="onSave();return false;">

My onSave(); function did return false, but since it was doing the redirection, I had to put the return false after the onSave(); (explain why??)

Thanks!

Trying to stop form from redirecting after submit (return false & prevent.default are not working!)

First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...

$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});

That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...

HTML...

<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>

Javascript...

$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});

Stopping a refresh/redirect on form submission

Is your submission causing your redirection/ refresh ?

If you have to submit your form to update fields in your database, you'll have to submit your form. But if you don't want to refresh all your page, you should think of using Ajax, as your submission will not refresh your page

Example from jquery ajax doc :

$("#form").submit(function() { 
$.ajax({
url:'confidential-url',
method:'POST' ,
data:$(this).serialize() //submits your form information
});
return false; // prevent the server form submission
});

jQuery ajax documentation



Related Topics



Leave a reply



Submit