$('form.comment_form').submit(function(e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url : 'inc/process-form.php',
type: 'POST',
cache: true,
data:({
comment : $form.find('input[name="comment"]').val(),
pid : $form.find('input[name="pid"]').val(),
post_author : $form.find('input[name="post_author"]').val(),
date_comment : $form.find('input[name="date_comment"]').val()
}),
success : function(results) {
$('.show-results').html(results).slideToggle().delay(2000).slideToggle();
$form[0].reset();
$('#all-post').load('home.php #all-post li');
}
});
return false;
});
The code above is my "jQuery+AJAX" for comment form. When I am submitting the comment form, it works fine but when I am submitting it again within a second, it reloads the page.
You can use unbind method to stop submitting the form again.
Here is the code as a sample :
var $form = $('form');
$form.bind('submit', function(e){
e.preventDefault();
...
$.ajax({
...
success: function(){
...
$form.unbind('submit').trigger('submit');
}
});
});
or you can use the it in other way
by using $(document).on("submit", "form", function() { });
sample code :
$(document).ready(function () {
$(document).on("submit", "form", function() {
$('#content').fadeOut(100, function () {
$(this).html('
<img src="//mywebsite.com/spinner.gif"/>
<div style="display:inline;color:#1FAEFF">Loading...</div>
').fadeIn(100);
});
$.get('submit.server', $(this).serialize(), function (data) {
$('#content').html(data);
});
return false;
});
});
Related
I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});
Is it possible to hook a function to an html attribute?
For example:
HTML:
<form method="post" action="ajax.php" id="login-form" data-function="doSomething">
//...
</form>
JS:
function doSomething() {
alert('hello!');
}
$(document).on('submit', 'form', function(event){
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(result){
form.attr('data-function'); //<-- call the function defined in data-function here
}
});
});
Thanks in advance!
you can do this if you store the function in an object
const obj = {
doSomething() {
alert('hello!');
}
}
then you can call doSomething with
obj['doSomething']()
Currently i have a $(window).unload function which do some tasks on leaving that page. but i need these actions to be done only if a form is not submitted. This is what i have done so far`
$(window).unload(function () {
var flag=0;
$("#id-message-form").submit(function(){
flag=1;
});
if(flag!=1){
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
async: false,
data:{},
beforeSend: function() {
},
complete: function() {
},
success: function(data) {
}
});
}
});`
You could set a flag when a form is submitted - and then check that in your unload function.
// Set this globally
var formSubmit = false;
$('form').on('submit', function() {
formSubmit = true;
}
Then in your window unload function;
if(!formSubmit) {
// your code that submits the form
}
The issue is due to the scope of the flag variable and the submit handler. Place them outside the unload handler. I'd also suggest changing flag to a boolean value.
var formSubmitted = false;
$("#id-message-form").submit(function() {
formSubmitted = true;
});
$(window).unload(function() {
if (!formSubmitted) {
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
data: {},
async: false,
beforeSend: function() {},
complete: function() {},
success: function(data) {}
});
}
});
The submit() will no matter submit the form by default. You should try click() function to store flag value instead.
I would like to merge two JavaScripts. The first one is using ajax to send message and the second one to alert user about required field in the contact form.
I want to merge this two, maybe with an IF statement, so first to check all fields and then to send message.
1 with ajax JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function () {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
2 alert JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
});
From the answer below i have create the following code.
I made this link if someone wants to help. The alert works fine but the code not stop. It continue to load the rest code.
https://jsfiddle.net/L8huq1t1/
You can do this by the following code.
function checkValidation() {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
//e.preventDefault();
return false;
}
});
return true;
}
$('document').ready(function () {
$('form#contact-form').submit(function () {
if(!checkValidation()) {
return false;
}
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
But I give you a suggestion to use jquery.validate plugin which is better option. But if you still want to do like this, go ahead this is also works fine.
You can use jQuery Validation plugin that has a form submit handler where you can put your AJAX. Link to the plugin.
Your code should look something like this:
$('#contact-form').validate({
rules: {
your_input_name: {
required: true
}
},
messages: {
your_input_name: {
required: 'Field is required'
}
},
submitHandler: function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function() {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
return false;
}
});
i am newbie to jquery.I called a ajax when submit the form.But form submits before ajax complete the request.How to fix this issue? Below is my code
$("#formSearch").submit(
function() {
if (checkUserNumber($("#UserNumber").val())) {
$.ajax({
type : 'post',
url : 'CheckDetails.do',
data : {
userNumber:$("#UserNumber").val()
},
success : function(data) {
if (data == 'EI') {
$("#ErrMsg").text(
'User Number does not exist');
return false;
} else {
return true;
}
}
});
} else {
return false;
}
});
Any help will be greatly appreciated!!!
use event.preventDefault(); to prevent the form submission.
$("#formSearch").submit(
function(event) {
event.preventDefault();
...
...
....
});
You can apply trick to achieve your requirement, add a data attribute to target form as follows
<form id="formSearch" data-prevent-default="1">
set default value to data-prevent-attribute=1 than you can rewrite your jquery submit function as follows:
$("#formSearch").submit(function (e) {
if ($(this).data("prevent-default") === 1) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'CheckDetails.do',
data: {
userNumber: $("#UserNumber").val()
},
success: function (data) {
//on success change the value of data attribute to 0
$("#formSearch").data("prevent-default", "0");
$("#formSearch").submit(); //than call form submit again
}
}).fail(function () {
});
}
//otherwise it will submitted by default
});