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()
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.
When I run submit, an alert message occurs as many times as you send it before you reload.
For example.
first run submit occur success message
not refresh second run submit two repeat occurs success message
not refresh third run submit three repeat occurs success message
...
not refresh n run submit n repeat occurs success message
Why does it run like this?
How can I solve this problem?
My code is as follows.
$(document).ready(function() {
$('#my_modal').on('show.bs.modal', function(e) {
var p_index = $(e.relatedTarget).data('p_index');
$(e.currentTarget).find('input[name="p_index"]').val(p_index);
$("button#submit").click(function() {
$.ajax({
type: "POST",
async: false,
url: "../receipt/send.php",
data: $('form.send_p_index').serialize(),
success: function(data) {
alert("success")
$("#send_p_index")[0].reset()
$("#my_modal").modal('hide');
},
error: function() {
alert("Error");
}
});
});
});
}
WRONG
$(document).ready(function() {
$('#my_modal').on('show.bs.modal', function(e) {
var p_index = $(e.relatedTarget).data('p_index');
$(e.currentTarget).find('input[name="p_index"]').val(p_index);
$("button#submit").click(function() {
$.ajax({
type: "POST",
async: false,
url: "../receipt/send.php",
data: $('form.send_p_index').serialize(),
success: function(data) {
alert("success")
$("#send_p_index")[0].reset()
$("#my_modal").modal('hide');
},
error: function() {
alert("Error");
}
});
});
});
}
CORRECT: Put this outside of modal.shown because every time the modal shown, it will write a submit function that repeats as many as it shown.
$(document).on('click', 'button#submit', function() {
$.ajax({
type: "POST",
async: false,
url: "../receipt/send.php",
data: $('form.send_p_index').serialize(),
success: function(data) {
alert("success")
$("#send_p_index")[0].reset()
$("#my_modal").modal('hide');
},
error: function() {
alert("Error");
}
});
});
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");
I need to implement AJAX file uploading interruption by click on cancel button.
Here's code which I'm trying to use:
var reqx=null;
function ajax_upload(){
reqx = $.ajax({
type: 'post',
url: "/file.php",
data: new FormData( $('#file')[0] ),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log("success");
},
error: function (data) {
console.log("error");
}
})
}
$('input[type=file]').change(function () {
ajax_upload();
});
$('#cancel').click(function(){
if (reqx != null){
reqx.abort();
reqx = null;
}
});
Clicking on Cancel button causes an error:
Uncaught TypeError: reqx.abort is not a function
Need help to find out mistake in my code. Thanks.
IIRC your looking for resolve(). http://api.jquery.com/deferred.resolve/ It causes the deferred to immediately complete and process any done logic.
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
});