I have a form which has a save and continue button. So I want the third click to submit the data. I have written the following code for it. But the submit portion doesn't work.
$(document).ready(function(){
var datastring="";
var d1= $( "#Submit3" ).mousedown(function() {
alert("Event occurred");
datastring = $("#reg_form").serialize();
console.log(datastring);
});
function submit()
{
$('form').submit(function(){
$.ajax({
type: "POST",
url: "reg.php",
data: datastring,
success: function(data) {
console.log('Data sent');
}
});
});
}
$.when(d1).done(submit());
});
Try the following code
$(document).ready(function(){
$( "#Submit3" ).on("click", function() {
alert("Event occurred");
dataString = $("#reg_form").serialize();
console.log(dataString);
submit(dataString);
});
function submit(dataString)
{
$.ajax({
type: "POST",
url: "reg.php",
data: dataString,
success: function(data) {
console.log('Data send');
}
});
}
});
You need to make the button type of the third button to "submit" and the type of other two buttons should be "button" just like this.
<button type="button">Save</button>
<button type="button">Continue</button>
<button type="submit">Submit</button>
So that when you click on the other two buttons form will not be submitted. Only on the click of third button, your form will be submitted. Here is the script to submit the form
$("form").submit(function(e){
e.preventDefault();
var formData=$("form").serialize();
console.log(formData);
$.ajax({
type: "POST",
url: "register.php",
data: formData,
success: function(response) {
console.log('Data send');
}
});
});
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.
This is very simple but I am missing something here and could not figure out. I have a submit button with an addEventListener so when you click, it will call to php file. However, this is what i get
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
but it works if i place ajax outside of addEventListener. I am so confused
index.html
<input type="submit" value="Submit" id="submit"/>
index.js
$(document).ready(function() {
document.getElementById('submit').addEventListener('click', function () {
$.ajax({
type: 'GET',
url: 'index.php',
data: {'user_id': '123213'},
complete: function (response) {
alert(JSON.stringify(response));
}
})
})
});
index.php
echo json_encode("got to php file!!!");
Try this instead:
$('#submit').click(function(){ // Click handler
$.get('index.php',
{'user_id': '123213'}, // Data payload
function(resp) { // Response callback
alert(JSON.stringify(resp));
});
return false; // Prevent default action
});
$(document).ready(function() {
$('#submit').on('click', function () {
$.ajax({
type: 'GET',
url: 'index.php',
data: {'user_id': '123213'},
})
.done(function(data) {
console.log("success");
})
.fail(function(msg){
console.log("error");
});
})
});
Try this it will work
I have form that is posted through AJAX. If I don't use any other JavaScript libraries it works like a charm.
Now I'm using Bootstrap and jQuery and it won't fire.
The code:
$(function() {
$('form').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'ajax-post.php',
data: $(this).serialize(),
alert($(this).serialize());
success: function() {
$(".alert").show(0).delay(2000).hide(0);
}
});
e.preventDefault();
});
});
You can not put alert between two properties data and success, remove alert():
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'ajax-post.php',
data: $(this).serialize(),
success: function () {
$(".alert").show(0).delay(2000).hide(0);
}
});
e.preventDefault();
});
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();">
How can I merge two separate javascripts in one?
I have two separate javascripts. One sends form data to post.php page without page refresh AND refreshes DIV content with (div.php) , but second disables corresponding form submit button. How can I merge this code in one? (not that I have many forms with different id’s in one page).
Problem is on IE9, where this script double submits data!!!
$(function() {
$('form').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'post.php',
data: $(this).serialize(),
success: function(returnedData) {
$('#sidebar').load('div.php');
}
});
e.preventDefault();
});
});
$(document).ready(function() {
$('input[type=submit]').click(function() {
$(this).prop("disabled", true);
$(this).val("Selected");
$(this).closest('form').trigger('submit');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Remove
</script>
<script>
And you're done ;-)
I would go a bit further though:
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $(this).serialize(),
success: function (returnedData) {
$('#sidebar').load('div.php');
}
});
return false;
});
$('input[type=submit]').click(function () {
$(this).prop("disabled", true);
$(this).val("Selected");
$(this).closest('form').trigger('submit');
});
});
To combine the two code just remove the code
});</script><script>$(document).ready(function () {
to prevent double form submission in ie9, use return false:
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $(this).serialize(),
success: function (returnedData) {
$('#sidebar').load('div.php');
}
});
return false;});