Multiple form submission with ajax and jquery - javascript

I am having an issue where I have two forms on the one page that are submitted using Ajax and Jquery. My code works to submit the forms the only issue is when one form is submitted it shows the confirmation message on the other form as well, even though that form has not been submitted.
Basically I have hidden a div with the confirmation message and it appears after the message successfully goes through. Does anybody know how I can stop the confirmation message appearing on the form that hasn't submitted. Here is the code -
function jqsub() {
//Form 1
var $form = $('#catwebformform39698');
var $messagebox = $('#hide-message');
var $successmessage = " ";
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg) {
$messagebox.append($successmessage);
$messagebox.delay(800).fadeIn(550);
$form.fadeOut(250);
}
});
//Form 2
var $form2 = $('#catemaillistform1628');
var $messagebox2 = $('#hide-message2');
var $successmessage2 = " ";
$.ajax({
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg) {
$messagebox2.append($successmessage2);
$messagebox2.delay(800).fadeIn(550);
$form2.fadeOut(250);
}
});
}
Any pointers/ideas appreciated.
Cheers
Nik
Edit *
I had tried to add another jqsub() function but the system I am using will only allow one. So essentially I was hoping I could stop the process with some kind of logic within the code or similar. So essentially they have to exist in the one function.

Are you sure both form have not been submitted? Looking at your code, it looks like they're both submitted by that one function. javascript is asynchronous, so the 2nd form would submit right after the first one, w/o waiting for the first one to finish.
If you wanted to submit then sequentially, you would have to do this:
function jqsub() {
jqsub1();
function jqsub1() {
//Form 1
var $form = $('#catwebformform39698');
var $messagebox = $('#hide-message');
var $successmessage = " ";
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg) {
$messagebox.append($successmessage);
$messagebox.delay(800).fadeIn(550);
$form.fadeOut(250);
jsub2();
}
});
}
function jsub2() {
//Form 2
var $form2 = $('#catemaillistform1628');
var $messagebox2 = $('#hide-message2');
var $successmessage2 = " ";
$.ajax({
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg) {
$messagebox2.append($successmessage2);
$messagebox2.delay(800).fadeIn(550);
$form2.fadeOut(250);
}
});
}
}

Well, it's obvious.Your putting both the submit events inside a single function (jqsub).
you just need to separate them. like this:
function jqsub(){
//Form 1
var $form = $('#catwebformform39698');
var $messagebox = $('#hide-message');
var $successmessage = " ";
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg) {
$messagebox.append($successmessage);
$messagebox.delay(800).fadeIn(550);
$form.fadeOut(250);
}
});
}
function jqsub2(){
//Form 2
var $form2 = $('#catemaillistform1628');
var $messagebox2 = $('#hide-message2');
var $successmessage2 = " ";
$.ajax({
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg) {
$messagebox2.append($successmessage2);
$messagebox2.delay(800).fadeIn(550);
$form2.fadeOut(250);
}
});
}
EDIT: In that case you must somehow determine which form is being submitted. You can pass the id of the form being submitted to the function and then use a switch statement and perform the action respectively. Check this link. your CMS must somehow provide options for this kind of operation.

Well it seems to me that since both AJAX calls are inside the same function jqsub() they are both submitted and that's why you see the confirmation on the second form too. It would be easier to help if you post the code when you submit the form but I think that the problem lies there.

Related

Passing javascript variables(array) to php

I have a function where the user inputs are stored in a variable in javascript.
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
var bookseats = seat;
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
});
});
When the user clicks on the #btnsubmit button, I want to send this variable(actually an array) to a PHP file named confirm.php.
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
In my PHP file, I've written the code to get the sent variable as follows.
$bookseats = "";
if(isset($_POST['bookseats']))
{
$bookseats = $_POST["bookseats"];
print_r($bookseats);
}
When executed, nothing happens in the PHP file(doesn't print the bookseats).Is there something wrong with this code?
You're not using a "success" callback to get the output of the PHP code. See success callback
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
success: function(data) {
console.log(data); // or alert(data);
}
});
Also, I think you should stop the propagation of the default behavior of the button, to prevent the browser to redirect the page to the form's action URL:
$('#btnsubmit').click(function(ev) {
ev.preventDefault();
As #Malovich pointed out, as of jQuery 1.8, you could also use .then():
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats}
}).then(function(data) {
console.log(data); // or alert(data);
}, function(){
console.log("Error");
});

Yii2 Ajax Submission not working

Iam new to Yii2 and Ajax
I want to add multiple job for a work ,for that I pass id to WorkJobs Controller
This is my code for ajax submission
<?php
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {
var form = $(this);
if (form.find(".has-error").length) {
return false;
}
$.ajax({
var jobid = "<?php echo $id;?>";
url: form.attr("work-jobs/create&id="+jobid),
type: "post",
data: form.serialize(),
success: function(errors) {
alert("sdfsdf");
// How to update form with error messages?
}
});
return false;
});'
);
?>
But it's not working ,I don't know what's wrong in my code ,please help ...........
change your code like below
<?php
$url=Yii::$app->urlManager->createUrl(['work-jobs/create','id'=>$id]);
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {
var form = $(this);
if (form.find(".has-error").length) {
return false;
}
$.ajax({
url: "$url",
type: "post",
data: form.serialize(),
success: function(errors) {
alert("sdfsdf");
// How to update form with error messages?
}
});
return false;
});'
);
?>
Building off jithin's answer, make the following changes to your $.ajax() call
Make sure your URL is in quotes. It is a common mistake to forget to quote the URL when interspersing it with PHP. [jithin]
Unlike jithin's answer, you should do the following
instead of responding to the beforeSubmit event, handle the submit event. This would allow the Yii clientsoide validations do their job
the ajax.success callback takes data as the argument; not error, there's the ajax.failure callback for errors
Try using createAbsoluteUrl() in url like this:
url: "<?php echo Yii::app()->createAbsoluteUrl(\"work-jobs/create&id=\")"+jobid

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

Looped ajax only submits sometimes

I am working on a dynamic page with multiple forms that can be added and removed by the user. My jquery script goes and finds all 'form' elements and submits them with jquerys ajax method. Here is the script
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
}
});
}
});
window.location.replace('/campaign');
});
})(); //end SIAF
});//end document.ready
The problem occurs that only sometimes the form submits, I can get it to if I click the save button a few times or if I remove the window.location.redirect that runs at the end, I suspect it is something to do with the redirect occurring before the submit, but I am not sure of a solution after going through some of the documentation
You are being caught out by the asynchronous nature of Ajax. Ajax does not work in a procedural manner, unfortunately. Your success method is called as and when the Ajax request has completed, which depends on your internet connection speed and how busy the server is.
It is entirely possible, the javascript completes its each loop and the first ajax request is still sending or waiting for a response. By when the javascript is ready to do a window.location call.
Edit:
Added code to check the number of forms, and the number of ajax requests, once they have all run, it will redirect
$(document).ready(function () {
(function (){
var id = $(document).data('campaign_id');
var numForms = $('form').length;
var numAjaxRequests= 0;
$(document).on('click', '#save-button', function () {
$('form').each(function (){
var data = new FormData(this);
var form = $(this);
if(!form.parent().hasClass('hideme'))
{
$.ajax({
url: form.attr('action'),
type: 'POST',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log('form submitted '+count);
numAjaxRequests++;
if(numAjaxRequests == numForms) {
window.location.replace('/campaign');
}
}
});
}
});
});
})(); //end SIAF
});//end document.ready

Categories

Resources