I have a form which has a submit button. If I click this submit button then JSON will be posted to a webservice through AJAX:
$("#msform").submit(function (e) {
$.ajax({
url: 'https://example.com/webservice',
type: 'POST',
data: formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function (data) {
console.log(data);
}
});
});
The webpage will also load and go to another page.. While loading the user can click multiple times on the Submit button, if he does that then for multiple times the AJAX post will be done to the webservice.
I tried this code to fix this but it does not work:
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
$(this).on('submit', function (e) {
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
$('#msform').preventDoubleSubmission();
Any idea why double posting is not prevented??
The solution is to use a variable called wasSubmitted which verify if ajax request was already sent.
var wasSubmitted = false;
$("#msform").submit(function (e) {
if(!wasSubmitted) {
wasSubmitted = true;
$.ajax({
url: 'https://example.com/webservice',
type: 'POST',
data: formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function (data) {
console.log(data);
}
});
return wasSubmitted;
}
return false;
});
I think a simple preventDefault would be enough
$("#msform").submit(function (e) {
e.preventDefault();
$.ajax(..)
The solution, that comes to my mind first, is to disable the button onclick with JS.
document.getElementById("btn_id").setAttribute("disabled","disabled");
Related
I am trying to perform an ajax call inside a form (a Drupal node edit form) , but it seems when performing the call, it submits the form for some reason. Here is a sample code:
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: {"text": jQuery("#edit-body").html()
},
success: function(result){
console.log(result);
}
});
I can replicate this just by executing it in the console, but I attach this to a button click function inside the form. Any tips on preventing the form from submitting, on a POST ajax call?
Here is the full code as requested
jQuery("#edit-body").before('<div id="proofread_bot-button-holder"><button type="button" id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>');
jQuery("#proofread_bot-submit").click(function(event){
event.preventDefault();
jQuery("#proofread_bot-button-holder").append("<img id=\"proofread_bot_throbber\" src=\"sites/all/modules/proofread_bot/images/throbber.gif\" />");
jQuery.ajax({
type: "POST",
url: "proofread_bot/check",
dataType: "html",
data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
},
success: function(proofread_result){
jQuery("#proofread_bot-submit").after(proofread_result);
jQuery("#proofread_bot_throbber").remove();
}
});
});
You need to override form's onsubmit event to prevent submitting:
$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (isValid) {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
e.preventDefault();
return false;
});
By calling
e.preventDefault();
return false;
You prevent synchronous postback from occurring.
UPDATE:
If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?
If you are using a input type="submit" button, then you need to do a return false; at the end of the function to prevent it from submitting.
Another solution is to e.preventDefault() on the button click
$(".button").click(function(e){
e.preventDefault();
return false;
});
you can change submit button type to just a button type and add "onclick" event to that button.
input type="button" value="savebutton" onclick="return doThisOnClick();"
function doThisOnClick(){
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
I think this is most straightforward.
I'm using this code to submit a form using Ajax:
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
CheckRequired();
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
This function checks for required classes in form elements
function CheckRequired(event) {
var $form = $(this);
var emptyElements = $form.find('.required').filter(function() {
return this.value === ''
});
if(emptyElements.length > 0) {
event.preventDefault();
emptyElements.addClass("EmptySelect").attr('title', 'This field is required');
//alert(emptyElements.attr("id"));
alert("One or more fields cannot be blank");
return false;
}
}
I then have this code which automatically checks all my forms for required fields using the above function:
$(document).ready(function () {
$('form').on('submit', CheckRequired);
});
It works fine on forms that POST to another page.
When using the Ajax submit code, its display the alert when there is an error, but its still submitting the form.
You might want to enclose the return of CheckRequired into an if() structure :
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
if(CheckRequired.call(this,e)) { // this should refer to the event target element, i.e. the form element, providing context for the function
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
}
});
});
});
You can simply add onSubmit="return CheckRequired()" in your form.
If the 'CheckRequired()' return false, you need to stop the script by returning false.
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
e.preventDefault();
if (!CheckRequired(e)) {
return false;
}
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
Two ways to approach this:
A) Javascript
$(document).ready(function(){
$("#SubmitTicket").submit(function(e){
if(!CheckRequired()) return false; // THIS!
e.preventDefault();
dataString=$("#SubmitTicket").serialize();
$.ajax({
type: "POST",
url: "?SubmitTicket=1",
cache: false,
data: dataString,
success: function(res) {
if(res.indexOf("success")!=-1) {
//window.location.href = res.substr(8);
$("#CreateNewTicket_Body").html(res);
$("#CreateTicket").hide();
}
}
});
});
});
B) HTML:
<form id="SubmitTicket" onSubmit="return CheckRequired();">
I work with Telerik and when I submit changes from my grid I want to check some data with an AJAX call and then, if the data is OK continue the submit.
I don't really know how the data is submitted but I get it works like a classic form. Is-it possible to "pause" and "restart" the post ?
function onSubmit(e) {
// Pause Submit
$.ajax(
{
url: '/MyController/MyAction/',
type: 'POST',
dataType: 'json',
async: false,
success: function (check) {
if(check)
{
// Allow Submit
}
else
{
alert('error');
// Stop Submit
}
}
});
}
Try this way:
function onSubmit(e) {
$.ajax(
{
url: '/MyController/MyAction/',
type: 'POST',
dataType: 'json',
async: false,
success: function (check) {
if(check)
{
// Allow Submit
}
else
{
alert('error');
// stop at error
e.preventDefault();
}
}
});
} // end onSubmit
I need to call to function onsubmit in codeigniter.
One for submit and one for Access some id.
I like to know that how to call two function on submit, also i need to know how to submit form by ajax if i have true condition.
My ajax controller:
$(document).ready(function(){
add = function (){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
// i need to submit my form here...
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
});
jquery you can use :
$("#formId").submit(function(e){
e.preventDefault();
//your code
});
And in javascript
<form action="" method="post" onsubmit="return yourfunction()">
</function>
function yourfunction()
{
//your code
return true;
}
It doesn't matter whether you are using codeigniter or normal php simply use Ajax, Check this link
$('input#submitbuttonid').click( function() {
$.ajax({
url: 'url to post data',
type: 'post',
dataType: 'json',
data: $('form#formid').serialize(),
success: function(data) {
...your data logic comes here
}
});
});
And simple Javascript ,
$('form#formid').submit();
you can handle you form submission by jquery. to do this you can use one of jquery plugin for this purpose. i refer JqueryForm plugin to you.
by this plugin you can do something like this:
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
var options = {
target: '#message_box_id', // target element(s) to be updated with server response
url: url // override for form's 'action' attribute
type: type // 'get' or 'post', override for form's 'method' attribute
dataType: null // 'xml', 'script', or 'json' (expected server response type)
clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
};
// bind form using 'ajaxForm'
$('#your_form_id').ajaxForm(options);
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
i don't know what exactly you want to do but maybe you can use before submit feature of this plugin to solve you issue. for example you can try this way
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: your_ajax_function,
success: showResponse // post-submit callback
url: url // override for form's 'action' attribute
type: type // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
};
// bind form using 'ajaxForm'
$('#your_form_id').ajaxForm(options);
your_ajax_function = function(){
$.ajax({
// your ajax body
});
}
});
//stop the form from submitting you can select form by adding a class or id
$('form').submit(function(e){e.preventDefault});
//when a button with id submit is clicked
//fire ajax
$('button#submit').on('click',function(){
// your ajax code
});
How can I make ajax/jquery submit the form in case of ANY ajax error?
I want the regular submit pageload php validation to take over, in case of any ajax error
If I try and replace 'validateform.php' with 'xxxxtest.nothing', the form does not submit, and js throws console error "POST http://example.com/xxxxtest.nothing 404 (Not Found)"
$('#myform').submit(function(e) {
var $theform = $(this);
$.ajax({
url: 'validateform.php',
type: 'POST',
cache: false,
timeout: 5000,
async: false,
data: $theform.serialize(),
success: function(data) {
$('#errordiv').html('<p class="error">' + data + '</p>');
$('#errordiv').slideDown();
},
error: function(e){
return true; // form should be submitted
}
});
return false;
});
jQuery ajax function is asynchronous, so return false is always exectuted. So, instead:
error: function(e){
$('#myform').unbind('submit').submit();
}
Updated based on comments below.
JSFiddle: http://jsfiddle.net/9Q2L2/
Check if this works to you:
http://jsfiddle.net/don/9Q2L2/3/
Create a second php file to send the form and run this php file if any ajax error.
Use the unbind and the submit again.
You should try:
$('#myform').submit(function (event) {
var $theform = $(this);
$.ajax({
url: 'validateform.php',
type: 'POST',
cache: false,
timeout: 5000,
async: false,
data: $theform.serialize(),
success: function (data) {
$('#errordiv').html('<p class="error">' + data + '</p>');
$('#errordiv').slideDown();
//prevent submit
event.preventDefault();
},
error: function (event) {
//form is submitted
}
});
//None of them should be placed here, the code is always executed
//event.preventDefault();
//return false;
});
More about preventDefault()