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
By clicking a button Its loaded a bootstrap modal. On the modal there have a form and on click save button I am trying to submit form by ajax call. At first time the ajax call trigger one time, but 2nd time the ajax url trigger two times. I see on firebug console section the post url is called multiple times.
Here Is my jquery code.
$(".show-modal").click(function() {
$('.upload-modal').modal();
$(".save-logo").click(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
data : data,
contentType: false,
cache : false,
processData: false,
url : "../../io/upload/"
}).done(function(rawData) {
$('.modal-header .close').click();
})
});
})
The problem is that you have your .save-logo click handler inside the .show-modal click handler. So every time the modal is shown, you attach another click handler to the .save-logo element. The code below should fix that problem:
$(".show-modal").click(function () {
$('.upload-modal').modal();
});
$(".save-logo").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: data,
contentType: false,
cache: false,
processData: false,
url: "../../io/upload/"
}).done(function (rawData) {
$('.modal-header .close').click();
})
});
$(function(){
var editUserId;
$('#edit-user-modal').on('show.bs.modal', function(e) {
editUserId = $(e.relatedTarget).data('userid');
});
$("#edit-user-form").submit(function(event) {
event.preventDefault();
var form = $(this);
var route = "/edit-user/" + editUserId;
if(validateEditUserForm()){
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(Response)
{
if(Response){
console.log(Response.status);
console.log(Response.message);
if(Response.status == 'success'){
$('#adduser-alert-box').hide();
$("#add-user-form")[0].reset();
$('#adduser-success-box').show();
$('#adduser-success-box').html(Response.message);
}
else{
console.log('User could not be added');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html(Response.message);
}
}
else{
console.log('No Response');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('No Response');
}
}
});
}
else{
console.log('Validation Error');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('Please Fill All the Fields Correctly');
}
});});
I faced the same issue and randomly i tried something .
so if you create a global variable to store the 'id' you pass from your button then store the id from the 'data' attribute of your button then it won't make multiple requests when clicked since you have declared the variable globally!
Hope it helps.
Hey guys and gals,
I have a form that I would like to use AJAX to submit. For the callback function basically what I want to happen is, the form elements disappear (.hide) and are replaced by a div element (which will ready success or something of that nature). I then want the function to pause for 5 seconds and then redirect to a different URL.
The AJAX request successfully submits (as I receive an e-mail to the specified address as I should) but the callback function is not carrying out properly. Any suggestions?
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(5000);
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
}
})
}
}
**
UPDATE #1
**
This is the only error code that I am getting when I initially load the website (I've heard these errors only pop up in the dev tools and do not affect the user?)
But then when I submit the form I get this error code
I've also updated my JavaScript to the below code, taking advice from a few people who posted, it's still not working 100% though
$(document).ready(function() {
var $form = $('form');
$form.submit(function(){
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
}
});
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000)
});
});
Joey
setTimeout usage is wrong.
See :
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000);
}
})
}
});
Further, the following should ideally be declared separately, if you want the user to click a link and go after ajax success.
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
I've form that submit data to external URL and the same time I want to save in my database. I've tried ajax submit and try to sumbit normal POST in ajax success.
Here my code:
<form action="http://www.blabla/post" method="post" id="myfrom">
.....
....
</form>
<script>
$('#myfrom').submit(function() {
e.preventDefault();
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit();
},
error: function(e) {
console.log(e);
}
});
});
</script>
But here Ajax is not working form will submit normal post only.
change this:
$('#myfrom').submit(function() {
to this:
$('#myfrom').submit(function(e) {
You have not passed the event in the argument so form gets submitted.
This is another way as i see:
$('yourButton').on('click', function(e){
e.preventDefault(); // stops the buttons behavior
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit(); // submits the form if success
},
error: function(e) {
console.log(e);
}
});
});
<script>
$('#postData').click(function(e) {
e.preventDefault();
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit();
},
error: function(e) {
console.log(e);
}
});
});
</script>
<form action="http://www.blabla/post" method="post" id="myfrom">
<input type="button" value="post" id="postData">
</form>
you try this one. make a button in place of submit button.
return false after ajax call to stop the normal form submit like this:
$('#myfrom').submit(function() {
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit();
},
error: function(e) {
console.log(e);
}
});
return false;
});
I am trying to update my database when the user clicks a certain link (links have different values, so when user clicks one link number goes up by 1, another by 2, and so on).
I need to submit a form to another page containing the data from #form with a variable behind it, but this function doesn't seem to be working.
JavaScript
function update_number(x) {
$.ajax({
type: "POST",
url: "update_likes.php",
data: $("#Form"+x).serialize(),
dataType: "json",
return false;
};
HTML
<input type='image' src='...' onclick'update_number(2);' />
Any help appreciated.
It seems that your JavaScript is not closed correctly.
Try changing your JavaScript with this:
function update_number(x) {
$.ajax({
type: "POST",
url: "update_likes.php",
data: $("#Form"+x).serialize(),
dataType: "json",
success: function(json) {
alert( json );
return false;
}
});
}
I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});