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
});
}
});
});
Related
I have a form that uses jQuery.validate.js plugin to validate and submit a form. The form contains a file upload.
I want to submit and upload the image with the validate.js but When I submit the form with the selected image, nothing happens. I've searched for solution, but the ones I got did not solve the problem.
// **EDIT**
// Add method to check imagesize
$.validator.addMethod("imageSize",function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param);
}, "This fileld is required.");
// END: **EDIT**
var addNewsForm, format;
addNewsForm = $("#newsPanel");
format = ['png','jpe?g','gif'];
addNewsForm.on("submit", function(e) {
e.preventDefault();
//validate form
$(this).validate({
errorClass : "error",
rules : {
news_image : {
required : true,
imageSize: 5242880,
accept : format
}
},
messages : {
news_image : {
required : "Please select an image for the news.",
imageSize : "Image size should not be greater than 5MB.",
accept : "Unsupported image format"
},
submitHandler : function(form) {
sendData = {
news_image : $("#newsImage")
}; // end of sendData
$(form).ajaxSubmit({
type : "POST",
data : sendData,
url : "action_news.php",
success : function(getData) {
$("#pageMsg").html(getData);
}
}); // end of ajaxSubmit
}, // end of submitHandler
}); // end of document ready
<form method="get" id="newsPanel" enctype="multipart/form-data">
<div id="pageMsg"></div>
<input type="file" id="newsImage" name="news_image" size="40" id="newsImage">
</form>
Any better way of achieving this?
You're missing a closing } for your messages object, right now the submitHandler is inside the messages object.
You're also missing a }) to close this function addNewsForm.on("submit", function (e) {.
Try using the code below and see if it works.
addNewsForm.on("submit", function (e) {
e.preventDefault();
//validate form
$(this).validate({
errorClass: "error",
rules: {
news_image: {
required: true,
imageSize: 5242880,
accept: format
}
},
messages: {
news_image: {
required: "Please select an image for the news.",
imageSize: "Image size should not be greater than 5MB.",
accept: "Unsupported image format"
},
},
submitHandler: function (form) {
sendData = {
news_image: $("#newsImage")
}; // end of sendData
$(form).ajaxSubmit({
type: "POST",
data: sendData,
url: "action_news.php",
success: function (getData) {
$("#pageMsg").html(getData);
}
}); // end of ajaxSubmit
}, // end of submitHandler
}); // end of document ready
})
HTML5 validation isn't working in Safari so I'm using Happy.js.
My form is still submitting via ajax in Safari though with the code below (here is JSFiddle).
How can I validate #email-input before sending the form with ajax?
The code below is checking if ($(this).hasClass('unhappy')) then don't submit form, if it doesn't have class unhappy then submit form. But I guess the problem is that it doesn't have class unhappy from the beginning.
used from this reference: isHappy.js allowing ajax call when not valid
$(document).ready(function() {
function ajaxEmailForm() {
$(".sendingEmailLink, .sentEmailLink").hide();
$('#email-form').submit(function(event) {
event.preventDefault();
var formserialize = $(this).serialize();
var submitButton = $('#submitEmailForm');
$.ajax({
type: 'POST',
url: 'https://formkeep.com/f/MYID',
accept: {
javascript: 'application/javascript'
},
data: formserialize,
beforeSend: function() {
$(".sendEmailLink").hide();
$('.sendingEmailLink').show();
},
complete: function() {
$(".sendingEmailLink").hide();
},
success: function(d) {
$('.sentEmailLink').show();
},
error: function() {
$('.notification-e--phone').slideDown("medium", function() {});
},
}).done(function(data) {
submitButton.prop('disabled', 'disabled');
});
});
};
$('#email-form').isHappy({
fields: {
'#email-input': {
required: true,
test: happy.email,
message: 'Please enter your full email address.',
errorTarget: '.email-input-error'
}
}
});
var is_unhappy = false;
$('#email-form div :input').each(function(i) {
if ($(this).hasClass('unhappy')) {
is_unhappy = true;
return false;
}
});
if (!is_unhappy) {
ajaxEmailForm();
};
});
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.
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".
I need to request additional credentials to a user when he clicks certain buttons and submits certain forms.
I way I am trying to do it is:
Intercept the submit event, abort it, and store a copy
Ask for the credentials with an prompt dialog (not the JS native one, so this is all non-blocking)
If user inputs the credentials, insert the fields into the event data and send it to the server.
My current code for AJAX requests is:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
if (ajaxOptions.type === "POST") {
$.current_request = jqXHR;
jqXHR.abort();
$.check_password_with_my_dialog();
}
});
$.check_password_with_my_dialog: function() {
$("#validate-password-prompt").dialog({
modal: true,
title: "input pw",
buttons: {
Ok: function() {
$.password = $("#validate-password-prompt input").val();
$.deliver_current_request();
return $(this).dialog("close");
},
Cancel: function() {
return $(this).dialog("close");
}
}
});
}
deliver_current_request: function() {
$.current_request.beforeSend = function(jqXHR, ajaxOptions) {
ajaxOptions.data = ajaxOptions.data.concat("&password=" + $.password);
};
$.ajax($.current_request);
}
The problem so far is that ajaxOptions.data is undefined, so I can't add my data.
And the requests seems to be going as a GET instead of POST.
Am I doing this the right way, or am I way of?
updated
Here is a way i can think of to accomplish answer for your question.
<form id="myForm" >
<button id="submit-form-btn">Submit</button>
</form>
<div id="validate-admin-password-prompt">
<input type="password"/>
</div>
In javascript,
function submitForm(pwd) {
var formData = $('form#myForm').serialize() + "&password=" + pwd;
$.ajax({
type: "POST",
url: "http://google.com",
data: formData,
dataType: "script"
});
alert("POSTed: " + formData.toString());
}
function alertDialog() {
$("#validate-admin-password-prompt").dialog({
modal: true,
title: "Admin password is required",
zIndex: 10000,
buttons: {
Ok: function() {
$(this).dialog("close");
var pwd = $("#validate-admin-password-prompt input").val();
submitForm(pwd);
},
Cancel: function() {
$(this).dialog("close");
alert('Not authorized to submit the form');
return false;
}
}
});
}
$("#submit-form-btn").click(function(e) {
e.preventDefault();
$ele = $("#validate-admin-password-prompt input");
if ($ele.val()==null || $ele.val().trim()=="") {
alertDialog();
} else {
submitForm($ele.val());
}
});