jQuery Validation plugin and ajax form submit - javascript

I have a simple multipart/form-data form submitted with ajax after validation using jQuery Validation Plugin.
I disable the submit button before submit and after successful form submission enable the submit button and reset all the form fields. The form code is working on Chromium Browser on a Debian Box.
Is there a better/cleaner way of doing this?
<form class="aForm" enctype="multipart/form-data">
File To Upload: <input class="aData" type="file" name="aData" /><br/>
Name of User: <input type="text" name="aName" class="aName" placeholder="Name"
/><br/>
Date: <input type="text" name="aDate" class="aDate" placeholder="Date" /></br/>
<input type="hidden" value="5f25c045bf33ac72fcf5f8bc23b4c862d220d385" name="csrfToken" >
<button class="aButton">Button</button>
</form>
$(document).ready(function(){
$(".aForm").validate({
rules: {
aData: {
required: true,
extension: "png|jpg",
},
aName: "required",
aDate: "required"
},
messages: {
aData: "No Data",
aName: "No Name",
aDate: "No Date"
},
submitHandler: function(){
$('.aButton').prop('disabled', true);
var formData = new FormData($('.aForm')[0]);
console.log(formData);
$.ajax({
url: 'ajax.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success:
function(data){
alert(data);
$('.aForm')[0].reset();
$('.aButton').prop('disabled', false);
},
error:
function(jqXHR, textStatus){
console.log(textStatus);
}
});
}
});
});

Above block of codes are working in live production without any problem. Tested on IE9 to IE 11, Chrome on windows and Linux. There are no Firefox users.

Related

Form submit issues using jQuery and Ajax

Actually I have 2 questions about form submit using jQuery and Ajax.
Currenlty, I am validating a login form using jQuery/Ajax request. I want to disabled the login submit button after logged in successfully completed. So that I am using following .js code but it's not disabled the submit button.
Questions
a) what is the issue in my js code ? why it's not disable the login submit button after logged in successfully ?
b) Using jQuery/Ajax for login is safe for security ? If not what I need to to and Should I add server side validation too ?
Thanks a lot :)
.js code for login :
// Login form
function login_form (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'login_process',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data == '<div class="alert alert-success"><strong>Successfully logged!.</strong></div>') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Login Process php page :
It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo '<div class="alert alert-success">';
echo '<strong>Successfully logged!.</strong>';
echo '</div>';
}
Html form :
<div class="container bellow-nav">
<div class="row">
<div class="col-md-6 content-area">
<h3>Login</h3>
<hr/>
<form role="form" method="post" id="login_form">
<div class="form-group">
<label for="email">Email addresse</label>
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="pwd" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="hidden" name="_token" value="<?php echo $form_token; ?>">
<input type="submit" name="submit" value="LOGIN" class="btn btn-booking" id="login_bottom" onclick="login_form(this,event);" >
</div>
<div class="form-group validation_msg">
</div>
<div class="fomr-group">
<label for=""><p>Forgot password?</p></label> |
<label for=""><p>Don't have an account? <a href="signup">Join now</p></label>
</div>
</form>
</div>
</div><!--main row-->
</div><!--main container end-->
One reason could be that the data may have some leading or trailing spaces.
You can extract only the text message from the data and use that for comparison
if ($(data).text().trim() == 'Successfully logged!.') {
$('#login_form')[0].reset();
$("#login_bottom").prop("disabled", true);
} else {
$("#login_bottom").prop("disabled", false);
}
For the second part, I assume the server side login is using a secured cookie to store the authentication information is so yes it is secured.
Use json response insted of HTML
Login Process php page : It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo json_encode(['message'=>'Success'])
}
$.ajax({
url: 'login_process',
type: 'POST',
dataType: 'JSON',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data.message == 'Success') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
First and for most, YOU MUST ADD SERVER SIDE VALIDATIONS. JavaScript can be disabled on the browser and your validations will be disabled when that happens. Javascript can also be edit on the browser and your validations will be useless js validations is only good for user friendly feeling and not for security.
All you have to do is set the disabled attribute to disabled value
$("#login_bottom").attr("disabled","disabled");
However I don't think you are going inside that if. you should console log something and make sure you are passing the if statement.

What about Dropzone.js within an existing form submitted by AJAX?

Ok, here is the scenario. I have already a form having some input fields, some radio buttons and an input type=file. There is a button for submitting the whole form using AJAX.
Everything was working fine, until i decided to change the input type=file with the more fancy DropZone.js
Now i have the following html code (a sample here):
<form enctype="multipart/form-data" id="test_form" name="test_form" class="form uniformForm">
<input class="form-control" type="text" value="" name="a-name" id="a-name" />
<label for="a-name">Field Name</label>
<div class="dropzone dropzone-previews" id="my-awesome-dropzone </div>
</form>
<button class="btn btn-primary btn-large" id="submitForm"> Submit </button>
I have the following js (jQuery), too:
$("button#submitForm").click(function(){
var fd = new FormData(document.getElementById("test_form"));
fd.append("label", "WEBUPLOAD");
$.ajax({
type: "POST",
url: "create_form.php",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
});
});
$("div#my-awesome-dropzone").dropzone({
url: "#",
paramName: "creative_file",
maxFilesize: 1,
autoProcessQueue: false
});
In documentation of Dropzone.js says that the dropzone div looks like <input type="file" name="file" />. The only difference is that i want to rename the input name as creative_file.
I have 2 question.
1) This doesn't work. When pressing the Submit button, i have FIREBUG opened and i check what it sends as POST. It sends everything except the files. No creative_file, no file at all.
2) If finally figured out how to make it works, is there any way to have a fallback with this implementation especially for the iOS or Android devices ?
1)
$("#salvar").on('click',function(e) {
if ($("#psl_titulo").val() == "") {
alert('Empty');
} else {
e.preventDefault();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
$("#my-awesome-dropzone").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.href = url_redirect;
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Ocorreu um erro ao salvar ao enviar os dados. Erro: ' + textStatus);
}
});
e.preventDefault();
});
$("#my-awesome-dropzone").submit();
}
}
});

FormData ajax upload on IE8 -> alternatives and how it works

I'm tyring to upload a picture with ajax, so I'm using FormData, but it's not working with IE8. I've looked about it and it's not possible to use FormData with IE8, but I've found nothing I've been able to use instead in order to make it work on IE8 and other browser. Could someone tell me what to do please, and how to do it ?
The form I'm trying to submit
<form id="addImgForm" name="addImgForm" method="post" action="#URL(Action('ChiliTest-ImageUpload'))#" enctype="multipart/form-data">
<input id="newImage" type="file" name="newImage">
<input type="hidden" name="MAX_FILE_SIZE" value="12345">
<span id="addImage" class="button-addImage" type="submit"><isTradConstant keyword="l_customizationsChiliEditor_AddImageButtonTitle" template="CustomizationsChiliEditor" init="Ajouter"></span>
</form>
Called on addImgForm submit
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
return false;
Ideally when i faced this issue, i checked for FormData in browser and if that returns undefined, then i went for form submission via an iframe.
We have used jquery plugin for the same and got resolved this issue.
It is too simple just use
$('#myForm').ajaxForm(function() {
});
instead of below call, it set all options automatically.
$.ajax({
url: myUrl,
type: "POST",
data: new FormData($(this).parent()[0]),
contentType : false,
async: false,
processData: false,
cache: false,
success: function(data) {
//do something
}
});
Hope this will work out, let me know if any hurdles during implementation. Make sure you added jquery plugin before using ajaxform function. Do not need to do anything for other browser it works for IE and other both.
You can use [jQuery Form Plugin][1] to upload files via ajax in IE 8 and your example code should be like this:
[1]:
$(document).ready(function() {
var options = {
beforeSend: function() {
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
$("#bar").width(percentComplete + '%');
$("#percent").html(percentComplete + '%');
},
success: function() {
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response) {
$("#message").html("<font color='green'>" + response.responseText + "</font>");
},
error: function() {
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
<script src="http://malsup.github.io/min/jquery.form.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<form id="myForm" action="/demo/Upload" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div>
</div>
<br/>
<div id="message"></div>

Validate and submit a form containing data and a file using ajax/jquery

I have a form containing data and a file input fields,
I want to submit and validate this form using jquery and ajax through one script.
Below is my form:
<form id="datas" method="post" enctype="multipart/form-data">
<input type="text" name="firstName" value="" />
<input name="pic" type="file" />
<button>Submit</button>
</form>
Now I have this code to validate the data
$('#datas').validate({
rules: {
firstName:{
required: true,
minlength: 2,
maxlength: 100
}
},
messages: {
firstName: {
required: "Please Enter first name",
minlength: jQuery.format("Enter at least {0} characters"),
maxlength: jQuery.format("Enter atmost {0} characters"),
}
}
});
Then I have a seperate code that could submit the form
$("#datas").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: sucess.php,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
QUESTION:
Please how can I combine these two scripts to validate the file and data fields and also submit to the success page.
You can set required attribute for the file field as well as such:
rules: {
...
pic:{
required: true
},

Jquery Validation : Submit button have to be clicked twice for form submission (fire fox)

I am using jquery validation plugin for US ZIPCODE CHECK ,its working fine,
but I have to push the submit button TWICE to get the form submitted,
Note : if I press enter that it submits the form properly, but it doesnt work with click event
I already have checked this stackoverflow answers but they didnt helped me out
Why do you have to submit twice before jQuery Validate submitHandler is triggered?
jquery validate need to click submit twice to submit form
jQuery using .on and .validate must submit form twice to validate
Below is my Javascript code
var ans;
$(document).ready(function(e)
{
jQuery.validator.addMethod("zipcode", function(e)
{
$.ajax(
{
url: "http://zip.elevenbasetwo.com",
cache: false,
async: false,
dataType: "json",
type: "GET",
data: "zip=" + $("#zip").val(),
success: function()
{
ans = true;
},
complete: function()
{
ans = true;
},
error: function()
{
ans = false;
}
}
);
return ans;
});
$("#register-form2").validate({
debug: true,
onkeyup: false,
rules: {
zip: {
required: true,
zipcode: true,
minlength: 5
},
email: {
required: true,
email: true
}
},
messages: {
zip: {
required: "Please enter a USA zip code",
zipcode: "Please enter a valid USA zip code"
},
// zip: "Please enter a valid USA zip code.",
email: "Please enter a valid email address."
},
submitHandler: function(form)
{
alert('hi');
form.submit();
}
});
});
Please mark that if I dont use ajax function in my custom method than it just works fine, but i am not able to solve it.
below is my HTML code
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" class="wpcf7-form" id="register-form2" novalidate>
<input name="email" required id="email" type="text" placeholder="Email*">
<input type="text" name="zip" id="zip" required size="40" maxlength="15" placeholder="Zip code* (USA only)">
<input name="Form_submit" class="btn btn-primary wpcf7-form-control wpcf7-submit" id="Submit" value="Sign-up" type="submit">
</form>

Categories

Resources