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
})
Related
jQuery validation is working fine but it's not working for array. Please check the working code in here.
http://jsfiddle.net/rq5ra/1050/
If I added array in input then it's not working.
html code
<form id="createprofile">
<input type="file" name="profilepic[]">
<input type="file" name="profilepic[]">
<input type="submit" />
</form>
jQuery code
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
jQuery(function ($) {
"use strict";
$('#createprofile').validate({
errorElement: "label"
, errorClass: "has-error"
, submitHandler: function (form) {
form.submit(); //return false;
}
, highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('has-error');
}
, rules: {
profilepic[]: {
extension: "jpg,jpeg"
, filesize: 300000, //500kb
}
},
messages: {
profilepic[]: {
extension: "Please upload only jpg, jpeg format"
,filesize: "Please upload maximum 500Kb"
}
}
});
});
Please help me to fix it.
Please add "profilepicp[]"
working code http://jsfiddle.net/rq5ra/1052/
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)}, 'File size must be less than {0}');
jQuery(function ($) {
"use strict";
$('#createprofile').validate({
errorElement: "label"
, errorClass: "has-error"
, submitHandler: function (form) {
form.submit(); //return false;
}
, highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('has-error');
}
, rules: {
"profilepic[]": {
extension: "jpg,jpeg"
, filesize: 300000, //500kb
}
, profileurl: {
remote: {
url: "http://localhost:8888/codeigniternew/edit/username_exists"
, type: "post"
}
}
, email: {
required: true
, remote: {
url: "http://localhost:8888/codeigniternew/edit/email_exists"
, type: "post"
}
}
},
messages: {
"profilepic[]": {
extension: "Please upload only jpg, jpeg format"
,filesize: "Please upload maximum 500Kb"
}
}
});
});
html code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form id="FORM_SEND_IMAGE">
<input type="file" id="file" />
<input type="submit" value="submit" />
</form>
jquery code
function getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isImage(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'png':
case 'gif':
//etc
return true;
}
return false;
}
$(document).on('submit', '#FORM_SEND_IMAGE', function(e) {
e.preventDefault();
e.stopPropagation();
function failValidation(msg) {
alert(msg); // just an alert for now but you can spice this up later
return false;
}
var file = $('#file');
if (!isImage(file.val())) {
return failValidation('Please select a valid image');
}
var form_data = new FormData($(this)[0]);
$.ajax({
url: base_url + 'gallery/add',
type: 'POST',
data: form_data,
dataType: 'json',
beforeSend: function() {
console.log('before');
},
error: function(error) {
console.log(error);
},
success: function(data) {
console.log(data);
},
complete: function() {
console.log('complete');
},
processData: false,
contentType: false
});
});
demo jsfiddle
I have a form with JQuery validator being applied to it. I wont post it all, but the code looks like the following
var validator = $("#my_form").validate({
errorPlacement: function(error, element) {
$( element )
.closest( "form" )
.find( "#error" )
.append( error );
},
rules: {
emailAddress: {
require_from_group: [1, '.datagroup'],
email: true,
maxlength: 40
},
mobileNumber: {
require_from_group: [1, '.datagroup'],
number:true,
minlength: 8
}
},
messages: {
emailAddress: {
maxlength: jQuery.validator.format("shorter")
},
mobileNumber: {
number: jQuery.validator.format("Please enter a number"),
minlength: jQuery.validator.format("Please enter a valid number")
}
},
groups: {
datagroup: "emailAddress mobileNumber"
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "php/main.php",
data: $(form).serialize()
})
.done(function (response) {
$('#results').html(response)
});
return false;
}
});
The problem is that the submit handler is passed the whole form, and then this data is serialized and sent to main.php. However,I no longer want the format it is submitting the mobileNumber in. The reason for this is that I am now using a plugin which will format this number for me, and to get the value of this, I need to do
var mobileNumber = $("#mobileNumber").intlTelInput("getNumber");
I can also grab the email using val() so this can be assigned to a variable as well. So how can I pass main.php the variables mobileNumber and emailAddress?
Thanks
You could do so, by manually constructing the data object like below.
$.ajax({
type: "POST",
url: "php/main.php",
data: {
'emailAddress': $("#mobileNumber").intlTelInput("getNumber"),
'mobileNumber': $("selector").val()
}
})
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 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
});
}
});
});