Dual submission of form creating issue with validation - javascript

my forms have dual submission.
Step 1. submission on my defined url with ajax
Step 2. allow form to behave as its default behavior.
Issue:
I am not providing any validation with my script. i am not using any plugin like jquery validate.
when submitting the form, the jquery validation is working (Which is if form already heve) but just after the ajax complete it is allow to submit the form.
That should not happens if validation is there.
I am providing this my script to my client to get the submitted form info in my platform.
Thats why i don't know which validation client will use or if they will not use or they will use any plugin for validation.
i just want to stop the submission if there is validation error..
I know there is issue with
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
return true;
Script part:
$("form[data-track=MySubmit]").on("submit", function(event) {
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData
dataType: 'json',
success: function(responce) {
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
return true;
}
});
});
more info :
its a double submission script..means first it will submit the form on one url which is not in form action then it will allow form to do its default behaviors like
Ist step to save the info using ajax on my url
and then in 2nd step if form have action to submit the form then do this or if form has ajax submission then do this or etc other form behavior on submit
Update :
There is 2 person
I am
My client
I am providing my form submission script to my client they have their own form to and own jquery/javascript.
So now i am giving them my script and asking to put it on your form with my way and once they will put , i will also get the detail of form after submit.
But I AM NOT PROVIDING ANY SCRIPT FOR VALIDATION..
they have own validation there could be any plugin or custom jquery/javascript.
My issue :
How can i stop form submission if there is validation from their form's own jQuery/Javascript ?

Inside Ajax Success function check again for form valid
if($("form[data-track=MySubmit]").valid()){
// the form is valid, do something
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
} else{
// the form is invalid
}

You can try
event.preventDefault();
Like this
$("form[data-track=MySubmit]").on("submit", function(event) {
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
crossDomain: true,
data: formInputData
dataType: 'json',
success: function(responce) {
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
}
});
event.preventDefault();
});

You can use jquery validate() method for this. we can pass submitHandler function which handles how the form submit is handled after form is found to be free of client side validations.
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
Example: Submits the form via Ajax when valid.
$("#myform").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
You can try this :
$("form[data-track=MySubmit]").validate({
submitHandler: function(form) {
var formInputData = $(form).serialize();
//the default form submit behaviour
$(form).submit();
//form submit via ajax on custom url
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData
dataType: 'json',
success: function(response) {
console.log('form is submitted');
}
});
}
});

You can try return false and event.preventDefault both at the same time + You can change the behavior of code when the forms return true.
dataCheck = false;
$("form[data-track=MySubmit]").on("submit", function(event) {
if(dataCheck === false)
{
event.preventDefault();
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData,
dataType: 'json',
success: function(responce) {
dataCheck = true;
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
return true;
}
});
return false;
}
});

try this
for validation you can use JQuery Validation Engine Plugin here:https://github.com/posabsolute/jQuery-Validation-Engine
$("form[data-track=MySubmit]").submit(function(event) {
event.preventDefault(); /////////added
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData, //////missing comma
dataType: 'json',
success: function(responce) {
$("form[data-track=MySubmit]").submit();
}
});
});

From what I understand, you want to submit your form with AJAX to url, where the validation happens and if it returns successfully, submit it a 2nd time to its default action.
If this is the case, then your code almost works, but you need to do two things:
Put event.preventDefault(); in your submit handler to prevent at the beginning the default action of the form, because we want us to trigger it only after AJAX returns successfully.
If AJAX returns successfully and you see that your form is not submitted a 2nd time, make sure that your form does not have a submit button named "submit", because that would hide the default submit action and $("form[data-track=MySubmit]").trigger( "submit" ); would not work! Rename your submit button to "submitBtn" or whatever.
BTW, you are missing a comma after data: formInputData

Have a hidden button with "default" submit. Once you are done with your processing ajax using jQuery, invoke the click event on the button.

Related

jQuery AJAX success not firing even though data is being captured

I have a form that I'm submitting by AJAX and trying to replace the form once it's been submitted with a success message.
Using this:
jQuery(function($){
var $form = $('#ajax_form'),
$message = $('#thanks');
$form.submit(function(e){
$.ajax({
type: "POST",
data: $form.serialize(),
url: $form.attr('action')
})
.done(function(data) {
console.log(data);
if (data.success) {
$form.hide();
$message.fadeIn('slow');
}
});
e.preventDefault();
});
});
when I click the submit button, nothing happens, and I don't get anything written to the console. But the form is hooked up to a database and I can see in the back end that submissions are being saved.
So why is that nothing within the done function is returning?

AJAX/JQuery: Submit form and call function without refreshing page

I'm attempting to use ajax/jquery to submit a form comprised of dropdown menus, with the intention of displaying information from a MySQL database based on the form input. Without ajax/jquery, the page functions properly. However, I don't want the page to refresh once the form is submitted, so that the selected dropdown options remain showing. My ajax/jquery is not very good, and I know this is where I'm having trouble. my code is as follows:
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(){
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
the function displayResults is the function that I want to call when the form is submitted, but as of right now, when i click submit, the form refreshes and no results are displayed. Any help would be greatly appreciated. Thanks in advance.
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(e){
e.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
This prevents the form from submitting by preventing the event from firing. In vanilla javascript you could return false on submit and it would be the same.
Try this way to submit your form and prevent default behavior of form submit using e.preventdefualt() which will prevent event from firing,To serialize form data use serializeArray() ,use success and error to debug ajax call.
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
console.log(data); //display data Results
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(errorThrown); // dispaly error
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
The .submit() it will be the same as use the submit button. You have to use a button with the click event.
<script>
$(document).ready(funtion(){
var data1 = $('#field1').val();
// the same with all the values
$('#button').click(function(){
$.ajax({
type: "POST",
data: ({dat1: data1} ),
cache: false,
success: function(data) {
displayResults();
}
});
});
});
</script>

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

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;
}

Using the jQuery validation plugin's submitHandler method properly

first a little bit of documentation from the jQuery validation plugin:
"Use submitHandler to process something and then using the default submit. Note that "form" refers to a DOM element, this way the validation isn't triggered again."
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: form.action,
data: 'current_password=' + form.current_password + '&new_password=' + form.new_password,
success: function(){
alert("succes");
}
});
}
So, naturally my ingenious piece of code isn't working. I'm trying to access the 'action' attribute and the two input fields from the form object, with no luck. How am I supposed to do this?
Try this instead:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: { current_password : form.current_password.value,
new_password: form.new_password.value }
success: function(){
alert("succes");
}
});
}
Currently instead of submitting the values of the elements it's literally calling a toString on them, so just add .value to get the values. Also we're passing data as an object here so it gets encoded, otherwise if for example the password had a & in it, the post wouldn't be correct.

Categories

Resources