How to stop form submit during ajax call - javascript

I can only modify the code in the ajax call.
The ajax call occurs when I click the submit in form named $('#form1').
$('#form1').submit(function () {
$.ajax({
url: 'some.php',
type: 'POST',
data: somedata,
success: function (msg) {
if (!msg) {
// I wanna to stop '#form1' submit here,how to do that? I can only modify the code in the ajax call.
}
}
});
});

You'll need to stop it BEFORE the success handler. Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late).
But yes, put return false at the end of your function.
function SubmitHandler(){
// Your AJAX call here
// blah blah blah
return false; // Stop form submit
}
If it's really important that it is in the success handler, then you could execute the call synchronously.

You can also use preventDefault()
http://api.jquery.com/event.preventDefault/

return false or event.preventDefault should help you:
$('#form1').submit(function(){
$.ajax({
url:'some.php',
type:'POST',
data:somedata,
success:function(msg){
if(!msg){
//i wanna to stop form1 submit here,how to do that? you can only modify the code in the ajax call
}
}
});
return false;
});
or:
$('#form1').submit(function(e){
e.preventDefault();
$.ajax({
url:'some.php',
type:'POST',
data:somedata,
success:function(msg){
if(!msg){
//i wanna to stop form1 submit here,how to do that? you can only modify the code in the ajax call
}
}
});
});

Put a
return false;
This should stop the function to continue

You need to prevent form submitting
onclick="ajaxcall(); return false;"
And do it in your code:
$.ajax({
url:'some.php',
type:'POST',
data:somedata,
success:function(msg){if(msg) $('#form1').submit();}
})

You can change button type from "submit" to "button" then submit form using jquery form.submit(); function according to your conditions. Consider the following example code below:
<script>
$(document).ready(function() {
$("#button-id").click(function() //on click at button
{
var sel=$("#input").val();
$.post("ajax-war.php",{jid:sel,rand:Math.random() } ,function(data)
{
if(data=='valid') //if correct login detail
{
$('#war_form').submit(); //Submit form
}
else
{
alert('not valid'); //will not submit form
}
});
});
});
</script>

Assuming the form's ID is #form1, you could bind a submit handler and return false from it:
$.ajax({
url:'some.php',
type:'POST',
data:somedata,
success:function(msg){
if(!msg){
$('#form1').submit(function(){
return false; // prevents form submit
});
}
}
})

Related

Javascript Sweetalert is sending form multiple times

my following javascript function is sending the form multiple times.
4 to 9 posts at the same time and I cannot get it right now.
Here is the function:
function formModal(url, id, type, text, send_type) {
$(document).ready(function () {
$('#' + id).on('submit', function (e) { //id of form
$.ajax({
url: url, // PHP file
data: $(this).serialize(),
type: send_type,
success: function (data) {
console.log(data);
// Success Alert
swal({
html: true,
title: text,
type: type,
timer: 1500,
showConfirmButton: false
});
setTimeout(function () {
// Refresh after 2 seconds
window.location.href = "";
}, 2200);
},
error: function (data) {
//Error Alert
swal("Oops...", "Something went wrong :(", "error");
}
});
e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
});
});
};
The function will be used in a HTML/ PHP Script:
<script> formModal('/dashboard_scripts/module/wiki/edit_wiki_article.php', 'edit_article', 'success', 'Artikel wurde gespeichert', 'GET') </script>
what are you doing in your code , why $(document).ready() inside the function formModal() and then inside that $(document).ready() you are binding submit handler which means every time you call the formModal() you are binding a submit event handler and thats the main reason of multiple submits of the form. you should either remove the submit handler from the function and make a simple ajax call or change
$('#'+id).on('submit', function (e) {
to
$('#'+id).off('submit').on('submit', function (e) {
Sweet Alert has nothing to do with the multiple submits of your form

Interplay between <form> and .ajax()

Folks,
I'm learning Ajax by tinkering. At first, I had a form with button, which made an Ajax call to a dummy controller action. The HTML and JavaScript on the client side.1
<form method="post">
<button name="btnSaveProject" title="When you save this project, it willl be available for 30 days.">
Save
</button>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$("button[name='btnSaveProject']").click(function () {
console.log("make ajax call");
$.ajax({
url: "/Project/Save",
type: "GET",
timeout: 8000,
cache: false
}).done(function () {
console.log("ajax call successful");
}).fail(function (jqXHR, textStatus) {
console.log("something went awry. " + textStatus);
}).then(function () {
console.log("always just in case");
});
});
});
</script>
A strange thing was happening when I clicked the button. The Ajax call would reach the server (I know thins because I had a break point in the controller action, which triggered). But neither neither .done(), nor .fail(), nor .always() was getting called back on the client-side.
Then I have moved the <button> out of the <form>, and now .done(), and .always() get called back as expected. There seems to be some interplay between the can Ajax call. What is this interplay? Where can I learn more about it? What do I have to do to be able to use Ajax inside a <form>?
Here's the server-side code, but I suspect that it's a non-factor.
// AJAX: /Project/Save
public ActionResult Save() {
System.Threading.Thread.Sleep(600); /// <bring-up>A bit of latency to make the Ajax call more noticeable.</bring-up>
return Json("lorem ipsum", JsonRequestBehavior.AllowGet);
}
1 I have stripped down the code and kept only the parts that I think are applicable to the question. If I have stripped down too much, please let me know: I'll post more code.
You can add a type to your button:
<button type="button" name="btnSaveProject"
or just prevent the defaults of button to submit the form with event.preventDefault():
$("button[name='btnSaveProject']").click(function (e) {
e.preventDefault();
// other code as is
});
Since the button is in a form its default click action is to submit the form, So in your case as soon as the ajax request is sent the actual page is submitted which I think is reloading the page causing the callback handler to unload that is why those are not getting called
One solution is to prevent the default action of the click event by calling event.preventdefault()
$(document).ready(function () {
$("button[name='btnSaveProject']").click(function (e) {
//prevent the default action of the button click which is to submit the form
e.preventDefault()
console.log("make ajax call");
$.ajax({
url: "/Project/Save",
type: "GET",
timeout: 8000,
cache: false
}).done(function () {
console.log("ajax call successful");
}).fail(function (jqXHR, textStatus) {
console.log("something went awry. " + textStatus);
}).then(function () {
console.log("always just in case");
});
});
});
But since you are using a form, instead of a button click event it will be better to use a form submit event like
$(document).ready(function () {
$("form").submit(function (e) {
//prevent the default action of the button click which is to submit the form
e.preventDefault()
console.log("make ajax call");
//your ajax code
});
});
Another option is to set the type of the button to button so that the form submit will not be triggered like
<button type="button" name="btnSaveProject" title="When you save this project, it willl be available for 30 days.">Save</button>

submitting form with jQuery/AJAX, cant stop page from refreshing on submit?

I'm having trouble getting my AJAX form to POST to my PHP Script without refreshing the page.
I have added e.preventDefault() both before and after the AJAX request but it doesn't appear to have any affect, which seems strange.
Here's my javascript:
// AJAX form submit
$("form[name=signoutRequestForm]").on("submit", function(e){
var cval = confirm.val().toLowerCase().replace(" ", "");
if( cval !== "yes" ) {
alert("You must accept the borrowing policy.");
}else{
var formData = {
validForm: true,
name_txt: name.val(),
productName_sel: prodName.val(),
signoutDateStart_txt: startDate.val(),
signoutDateEnd_txt: returnDate.val(),
additionalNotes_txtarea: addNotes.val(),
disclaimer_txt: confirm.val(),
recaptcha_challenge_field: recap_challenge.val(),
recaptcha_response_field: recap_response.val(),
studentUse: studentUse.val()
};
$.ajax({
type: "POST",
ulr: confLocation,
data: formData,
done: function(data){
$(".signoutRequestForm").remove();
$(".signout-form-container").html( data );
}
});
}
e.preventDefault();
});
Right now, when I hit submit, the page just appears to refresh without the form ever actually submitting.
From the comments, it was determined that the call to .on() was resulting in an exception (TypeError: undefined is not a function) and that you are using jQuery v1.5.2.
.on() was not added until version 1.7. For older versions, .bind() should be used instead.
just use return false
.....
e.preventDefault();
return false
});
Use return false; instead of e.preventDefault()

form won't submit correctly via jQuery and reverts to default behaviour

I've got a form withthe id offerForm which I submit via Jquery, but despite the 'return false' statement, the form doesn't submit via ajax. Any help will be much appreciated.
$(document).ready(function() {
$('#offerForm').live('submit',function(){
loadData(1);
});
function loadData(page){
$.post('get-offers.php', $("#offerForm").serialize() + '&page=' + page, function(data) {
//Do stuff
$('#demo').html(data.htmlOutput);
},'json' );
return false;
}
});
I recommend using the ajaxSubmit plugin located here: http://jquery.malsup.com/form/. It does exactly what you are trying to do.
In your case, you'd use something like:
$('#offerForm').submit(function()
{
var options = {
dataType: "json",
success : function(data) {
$('#demo').html(data.htmlOutput);
}
};
$(this).ajaxSubmit(options);
return false;
});
As a general rule, you should be stopping the event with event.preventDefault() rather than return false - they both work, but it's cleaner to use the event.
$(document).ready(function()
{
$('#offerForm').live('submit',function(event){ // add event as a parameter
event.preventDefault(); // and call preventDefault here
loadData(1);
});
function loadData(page)
{
$.post('get-offers.php', $("#offerForm").serialize() + '&page=' + page, function(data)
{
//Do stuff
$('#demo').html(data.htmlOutput);
}, 'json');
}
});

Form submit using jquery & passing values

I want to accomplish the following using jQuery:
frm_rooms.action="create_rooms.php?action=Save";
frm_rooms.submit();
I tried following jQuery but it doesn't work:
$('#frm_rooms').submit(function(event) <br/>{
$.post("create_rooms.php", { action: "Save" } );
});
Do it like this:
$('#frm_rooms').submit(function(event){
$.post("create_rooms.php", {action: "Save" }, function(){
alert("Data saved");
});
return false; //This is vital
});
If you want the parameters to be passed in the query string (GET method) use $.get instead of $.post.
EDIT: Thinking better, if you have fields inside your form that you want to be submitted, you should do:
$('#frm_rooms').submit(function(event){
$.post("create_rooms.php?action=Save", $(this).serialize(), function(){
alert("Data saved");
});
return false; //This is vital
});
Hope this helps. Cheers
Have you tried to use preventDefault() in your submit-function?
$('#frm_rooms').submit(function(event)
{
event.preventDefault();
$.post("create_rooms.php", { action: "Save" } );
});
Also be aware that if you also have an input-element within your form, which name is 'submit'. The submit-method of jQuery won't work.
Add return false; after $.post() to avoiding page reloading.
Try this -
$('#frm_rooms').submit(function(event)
{
$.post("create_rooms.php", {action: "Save" } );
event.preventDefault();
});
If you have an input element of type submit inside that form, then this method won't work. In that case, you will have to do something like following -
$('#mySubmitButton').click(function(event) // Suppose the id of that
// submit button is mySubmitButton
{
$.post("create_rooms.php", {action: "Save" } );
event.preventDefault();
});
If you want to provide success/failure message to the user, then modify the $.post method like this -
$.post("create_rooms.php", {action: "Save" }, function(data)
{
// data contains server response.
});
You can add .click() method to your button:
$('#button').click(function() {
//...
$('#form').attr('action', 'action.php');
return false;
})

Categories