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.
Related
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");
Following this previous link, I tried a new AJAX code, but still getting the same result (Data is inserted correctly, but can't stay in the same page).
$(function(){
$("#form1").on("submit", function(e){
$.ajax({
url: 'insert.php',
type: 'post',
data: $('#form1').serialize(),
dataType: 'json',
success: function(data) {
alert($('#form1').serialize());
});
e.preventDefault();
});
});
The form has an id="form1" and submit button inside this form is id="insert".
Any help is appreciated, need to fix this today.
The success function should be closed before closing AJAX function. You forgot to add a closing }:
$(function(){
$("#form1").on("submit", function(e){
$.ajax({
url: 'insert.php',
type: 'post',
data: $('#form1').serialize(),
dataType: 'json',
success: function(data) {
alert($('#form1').serialize() + "&insert=yes"); // add this
} //<--------------------------------------- You missed this
});
e.preventDefault();
});
});
You are sending the insert key as a parameter to post, but it doesn't work because you are not adding it while sending to AJAX. So add that and it works.
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
});
I have an ajax call that works great the first time the form is submitted after that all javascript on the page seems to break. As well as the form won't submit with ajax again.
Here is my ajax call:
$('form').submit(function(event) {
$('input:submit').attr("disabled", true).after('<p class="loading">Searching...</p>');
$.ajax({
type: "POST",
url: pathname,
data: $(this).serialize(),
success: function(data) {
$('#container').html("<div id='message'></div>");
$('#message').append(data).hide().fadeIn(1500);
},
});
event.preventDefault();
});
I'm getting no errors in my console. Any ideas what might be causing this?
I solved the issue, the main page content was changing. Which was causing the javascript to unload. So I need to use Jquery .on/.live and then it works. For what ever reason this worked fine on one server and not on another.
Use as below: No Need to define event.preventDefault();
$('form').submit(function(event) {
$('input:submit').attr("disabled", true).after('<p class="loading">Searching...</p>');
$.ajax({
type: "POST",
url: pathname,
data: $(this).serialize(),
success: function(data) {
$('#container').html("<div id='message'></div>");
$('#message').append(data).hide().fadeIn(1500);
$('input:submit').removeAttr("disabled");
},
});
return false;
});
Remove disabled after submitting the form. And remove the , mentioned by #JustinRusso.
$('form').submit(function(event) {
$('input:submit').attr("disabled", true).after('<p class="loading">Searching...</p>');
$.ajax({
type: "POST",
url: pathname,
data: $(this).serialize(),
success: function(data) {
$('#container').html("<div id='message'></div>");
$('#message').append(data).hide().fadeIn(1500);
$('input:submit').removeAttr("disabled");
}
});
event.preventDefault();
});