Validate and submit form with no page refresh - javascript

I'm using jQuery validation and processing the form via ajax so I can avoid a page refresh. The problem I am running into is that I can't figure out where to place the ajax code in the validation function so that the form won't send data until it's been validated.
For example:
$('#ticket_purchasing').validate({ // initialize the plugin
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
phone: {
required: true,
digits: true,
},
email: {
required: true,
email: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = "All fields in red must be filled*";
$("div.error-message span").html(message);
$("div.error-message").show();
} else {
$("div.error-message").hide();
}
},
submitHandler: function (form) { // for demo
// Do stuff here
}
});
$('form#ticket_purchasing').on('submit',function(e) {
//Send the serialized data to mailer.php.
$.ajax({
url:'ticket-purchase.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
// $('#sponsorship_request').slideUp();
// $('#ticket_purchasing').hide();
// $('.seats-form').fadeIn(1000);
},
error:function(data){
$("ticket_purchasing .error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
//$.post("mailer.php");
//Take our response, and replace whatever is in the "form2"
//div with it.
// $('#form2').show();
});
As you can see above I have both functions separated from each other, and because of this the form is submitting the data (which emails the information) even though it's not been validated yet. I tried using form.submit(); as show in the validator documentation, and putting the ajax code in there, but it was a no go with errors I couldn't solve.
Advice? I'm probably going at this all wrong haha.
Edit: Just added html for the form: https://gist.github.com/adrianrodriguez/26b6beee8bf5ba85a8ce
To be clear, the form works fine without the validation portion, meaning I can submit and collect the data without a page refresh without the use of the validation plugin.

Remove your $.ajax call as the actual form submission should happen after validation in the validate.submitHandler.
$('form#ticket_purchasing').validate({
//validation rules here
//invalid handler goes here
submitHandler: function(form) {
$.post('ticket-purchase.php', $('#ticket_purchasing').serialize(), successCallback());
}
});
BTW, changed your $.ajax to a $.post

Thanks for everyone's help. I eventually realized that I was going at it all wrong and found this answer:
submitHandler: function (form) { // for demo
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(data) {
console.log(data);
// Do stuff here
//$('#ticket_purchasing').hide();
//$('.seats-form').fadeIn(1000);
}
});
return false; // kill page refresh
}
Instead of going the traditional way of the ajax submit I just had to use the "form" parameter already provided from jquery.validation.js and then grab data from its attributes.
Thanks for everyones help!

$( "#target" ).submit(function( event ) {
});
between this.

Related

Jquery form validation before Ajax request

I have gone through other threads and used one for reference but still I am not able to find the solution.
My question is:
I am calling a function on button click now that function has validation after validation I am trying to post data with ajax request in submit handler, problem is my fields are getting verified but Ajax request is not invoked.
<input type="button" value="Register" id="registerP" onclick="registerPatient()" class="form-control input-sm btn-success ">
function registerPatient(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: "patientName=" + patientName,
success: function(response){},
error: function(e){}
});
}
});
}
However if I am not using validation and calling Ajax directly i am able to post the data. Please suggest where I am going Wrong.
You can try like this which call jquery form validation and check if validated:
$(document).ready(function(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
}
});
});
function registerPatient(){
var IsValid=$("#patientRegistration").valid();
if(IsValid){
var patientName=""; //value for patient name
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: {"patientName": patientName},
success: function(response){},
error: function(e){}
});
}
}
Change your data syntax of ajax to this.
data: {patientName:patientName},
Make sure you have a parameter on catching method of the same name "patientName" to invoke its post from page on post.
This should work.
Also check if you get a patientName paramater value in your post. To do so first check by "alert" and pass the patientName parameter. You will know what you are getting and why post is not happening.

Stop jQuery Ajax Success from preventing form submit

I am using jQuery validate with remote to check if an email address exists. Don't ask me why but I need it to redirect to a new page IF a match is found in the database (false), otherwise they should be able to use the form normally.
This code works perfect EXCEPT: if it returns true (meaning it didn't redirect) the form submit button doesn't do anything. I don't see any attributes assigned like disabled, but the form submission is defintely prevented. If I don't type anything in the email input, it will let me click the button.
rules: {
fullname: "required",
email: {
required: true,
email: true,
remote: {
url: "validate-email.php",
type: "post",
success: function(response) {
if(response === false){
window.location.href = 'new-page.html';
}
},
},
},
},
once I remove the success: section, form submission works normally so obviously it has something to do with what I did in there... Thank you in advance for your help!
Not sure if this is the best solution, but I was able to fix it by using this:
remote: {
url: "validate-email.php",
type: "post",
complete: function(data) {
if(data.responseText == "false"){
window.location.href = 'new-page.php';
}else{
return response;
}
},
Thank you for your help!

How to get a value from Ajax call to be used in a Bootbox button's function?

I am using Bootbox for my modals and I am having trouble in showing the form validation errors from an Ajax call to the modal. The callback function for the submit button on my modal calls the add_college function to submit the form via Ajax.
When there are validation errors, the modal is populated with validation errors. The problem is that the modal closes regardless if there are validation errors or not. I want the modal to not close only when there are no validation errors.
I know I can just return false in the callback function on my button when there are validation errors to not close it but I have no way of knowing if there are validation errors since I cannot return a value in the Ajax call since it is asynchronous. What is the proper way of doing it?
Here is my code:
$('#new-college-btn').click(function () {
bootbox.dialog({
title: "New College",
message:
''// <Insert long HTML form here>
,
buttons: {
add: {
label: "Add",
className: "btn btn-primary",
callback: function () {
var form_data = {
college_name: $('#college-name').val(),
college_initials: $('#college-initials').val(),
username: $('#username').val(),
password: $('#password').val(),
confirmation_password: $('#confirmation-password').val()
};
add_college(form_data);
}
},
cancel: {
label: "Cancel",
className: "btn btn-default"
}
}
}); // end bootbox dialog
});
function add_college(form_data) {
console.log(form_data);
$.ajax({
url: 'admin/add_new_college',
type: 'POST',
data: form_data,
dataType: 'JSON',
success: function (response)
{
if (response.error) { // there are form validation errors
// populate modal with validation errors here
} else {
// other data processing here
Result.success('College Successfully Added!');
}
},
error: function () {
console.log("fail");
}
});
}
If you want to control when the dialog closes, make sure the callback for your "submit" button always returns false. Then, in the done() (and probably fail()) callbacks for the ajax function, call bootbox.hideAll() to close the dialog (along with any other dialogs you may have opened).
If you want to only close the current dialog, do something along this line:
var dialog = bootbox.dialog({
/* rest of your options... */,
buttons: {
submit: {
label: "Submit",
callback: function() {
var data = [];
$.post('/url', data)
.done(function(result, status, jqxhr){
// if everything went well...
dialog.modal('hide');
})
.fail(function(jqxhr, status, error){
// etc.
});
return false;
}
}
}
});
Basically, create a reference to the dialog, which you can then use inside of the ajax callback.

jQuery and Ajax on Form submit - parse POST data

I have the following ajax jQuery code that on document.ready function downloads a file from ajaxFileDownload.php.
However, I would like it to instead of document.ready function use on submit of a form called reports. So when i click submit on my form name report, then it runs this, I would also like to parse the form field post variable called user_id to the php file.
Any ideas how this can be done?
I added: $('#reports').on('submit', function(e) {
How can I add the user_id post variable?
$(function () {
$('#reports').on('submit', function(e) {
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({
modal: true
});
$.fileDownload('ajaxFileDownloader.php?' + Math.random(), {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({
modal: true
});
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
});
});
Try adding these two lines inside the $.fileDownload block:
httpMethod: 'POST',
data: $(this).serialize()
like so:
$.fileDownload('ajaxFileDownloader.php?' + Math.random(), {
httpMethod: 'POST',
data: $(this).serialize(),
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({
modal: true
});
}
});
That should send all form data to the PHP script.
If you want to send just the one field, you could use $('#user_id') in place of $(this) assuming the field in question has id="user_id".

Jquery validate submitHandler is not getting called

I have a form with two buttons
a) Test - on click of the button a javascript function is called to verify a couple of credentials.
b) Create - on click of the button a javascript function is called to save the form.
#Messages("playauthenticate.project.create")
I have a form tag around these two submit buttons with no action.
name, description, accessKey and secretKey are the four fields in the form.
on clicking on the create button, I want to perform jquery validation and then submit the form but the jquery validation submitHandler is not getting called in the javascript function and there are no errors in the Error Console.
When I click on the create button, the create alert is shown and then the form resets and I am able to see all the parameters entered in the URL.
$("create").click(function() {
alert("create ");
$('#projectForm').validate( {
rules: {
name: {
minlength: 6,
required: true
},
description: {
required: true,
description: true
},
accessKey: {
minlength: 10,
required: true
},
secretKey: {
minlength: 15,
required: true
}
},
focusCleanup: false,
wrapper: 'div',
errorElement: 'span',
highlight: function(element) {
$(element).parents ('.control-group').removeClass ('success').addClass('error');
},
success: function(element) {
$(element).parents ('.control-group').removeClass ('error').addClass('success');
$(element).parents ('.controls:not(:has(.clean))').find ('div:last').before ('<div class="clean"></div>');
},
errorPlacement: function(error, element) {
error.appendTo(element.parents ('.controls'));
},
submitHandler: function() {
alert("hello");
var name = $('#name').val();
var description = $('#description').val();
var accessKey = $('#accessKey').val();
var secretKey = $('#secretKey').val();
var dataString = 'name='+ name + '&description=' + description + '&accessKey=' + accessKey+ '&secretKey=' + secretKey;
//alert(dataString);
$.ajax({
type: "POST",
url: "/demo/save",
data: dataString,
success: function(data) {
$('#result').html("<h2>demo created successfully!</h2>");
},
error: function(data) {
$("#result").html("<h2>Error!</h2>");
}
})
}
});
});
JSfiddle - http://jsfiddle.net/NJxh5/3/
Thank you
.validate() is the method for initializing the plugin. It's not a method of testing the form. Testing is automatic.
Therefore, get rid of the click handler. The click event is captured automatically by the plugin. If the form is valid, the submitHandler will fire.
Otherwise, you are doing it properly by placing your ajax inside the submitHandler callback.
$(document).ready(function () {
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
}
});
});
Working DEMO: http://jsfiddle.net/ACdtX/
With two different buttons and actions:
HTML:
<form id="projectForm">
....
<input type="button" class="button" value="TEST" id="test" />
<input type="button" class="button" value="Create" id="create" />
</form>
jQuery:
$(document).ready(function () {
$('.button').each(function () {
$(this).on('click', function () {
var action;
if ($(this).attr('id') == "test") {
action = 'test.php';
} else {
action = 'create.php';
}
$('#projectForm').submit();
});
});
$('#projectForm').validate({ // initialize the plugin
// rules & options
submitHandler: function(form) {
// ajax method
$.ajax({
url: action, // determined from click handler above
// ajax options
});
}
});
});

Categories