Pause then allow or not a post with JQuery - javascript

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

Related

Data disapearing after AJAX request [duplicate]

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.

How to stop setTimeout that was started outside the function that detects if the form was submitted?

My setTimeout starts when the page is loaded, I need to stop it as soon as the user clicks the button and submit the form, the variable seems to get lost and I can't stop, any tips?
my code
$(function() {
function atualiza(){
$.get('online.php?p=SMS',
function(resultado){
$('#onlineagora').html(resultado);
});
}
timer1 = setTimeout('atualiza()', 850);
$('#formsms').submit(function( event ) {
$.ajax({
url: 'aguardesms.php',
type: 'POST',
dataType: 'html',
data: $('#formsms').serialize(),
success: function(content){
clearTimeout(timer1);//STOP ATUALIZA
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
solved using setInterval/clearInterval
var timer1 = setInterval(atualiza, 850);
function atualiza(){
$.get('online.php?p=SMS',
function(resultado){
});
}
$('#formsms').submit(function(e){
e.preventDefault();
clearInterval(timer1);
$.ajax({
url: 'aguardesms.php',
type: 'POST',
dataType: 'html',
data: $('#formsms').serialize(),
success: function(content){
$("#DisplayDiv").html(content);
}
});
});

Prevent double submits form

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");

correct way to perform an ajax synchronous POST and then submit form

I've got my ASP submit button
<asp:button runat="server" Text="Submit" id="btnSubmitOrder" OnClientClick="return SubmitOrder()" />
My Javascript function, SubmitOrder(), needs to perform a POST, and then based on the success of that POST, either allow the form submission (return true) or cancel it (return false)
function SubmitOrder() {
$.ajax({
async: false,
type: 'POST',
url: strURL,
data: arrKeyVal,
contentType: 'application/json',
success: function (data) {
if (data.results.count > 0) {
return true;
} else {
return false;
}
},
error: function (jqXHR, exception) {
return false;
}
});
}
My concern is that since this is now deprecated, it may soon be obsolete.
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
So how should I handle this? Knowing that I need to wait for a response before allowing the form submission to proceed.
You can only cancel an event synchronously. One option is to not attach SubmitOrder to a form submit event, but rather just create a click handler, then actually submit the form in your ajax callback.
function SubmitOrder() {
$.ajax({
async: false,
type: 'POST',
url: strURL,
data: arrKeyVal,
contentType: 'application/json',
success: function (data) {
if (data.results.count > 0) {
$('form').submit();
}
}
});
}
...or you can do an Ajax submit of the form instead of a regular HTML form submit.
function SubmitOrder() {
event.preventDefault();
$.ajax({
context: this,
type: 'POST',
url: strURL,
data: arrKeyVal,
contentType: 'application/json',
success: function (data) {
if (data.results.count > 0) {
$('form').submit();
} else {
return false;
}
},
error: function (jqXHR, exception) {
return false;
}
});
}
EDIT: This function does not reference the form yet so you will need to select the form and then call submit.

JQuery required fields not stopping Ajax form submit

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();">

Categories