Jquery validator module and function call after success - javascript

First I don't have much experience with javascript and jquery :) I am just trying to find a quick way to connect jquery email validator module with a function that checks recaptcha. Here is my code:
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
Works fine! Inputs are validated.
Now after validation I need two things: First I need to call recapVerify(), after recaptcha gets validated I need to submit my form. This is the example I use: email method. I know I need to use submitHandler now but I can't figure out where and how?
Btw. this is recapVerify() function that I want to use:
function recapVerify(){
$.ajax({
type:'post',
url: 'captcha_check.php',
data: {
recaptcha_challenge_field:$('#recaptcha_challenge_field').val(),
recaptcha_response_field:$('#recaptcha_response_field').val()
}
}).done(function(data, textStatus, jqXHR){
if (data == 'success'){
$('#err').addClass('hidden');
//document.forms[0].submit(); // uncomment this line to submit your form
alert('Success, the form and reCAPTCHA validated, your form was submitted');
} else {
$('#err').removeClass('hidden');
}
}).fail(function(jqXHR,textStatus,errorThrown){
console.log('recaptcha or service failure');
});
}

use submitHandler on your jquery validate function. Debug is not needed. In essence this is the javascript you need.
$(document).ready(function(){
$("#test-form").validate({
rules: {
name: {
required: true,
},
email : {
required : true,
email : true
}
},
submitHandler : recaptchaVerify
});
});
function recaptchaVerify(form){
console.log(form);
alert("in submit handler");
}
According to the documents at jQuery validate
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.
Have also created a fiddle so that you can use it.

Related

Laravel - do not continue after form validator if ajax request

I want to create a ajax form validation that verifies that form data and gives user instant feedback before really submitting the form.
For this i added a javascript function on form submit:
<form id="x" onsubmit="return dosubmit(this)" action="{{ url('/x') }}" method="POST">
<script>
function dosubmit(form) {
$.ajax({
url: $(form).attr('action'),
type: 'post',
data: $(form).serializeArray()
}).done(function (data) {
form.submit();
}).fail(function (data) {
alert('error');
});
return false;
}
</script>
And i have custom a form validator request:
class X extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
];
}
}
When my ajax request fails everything works fine. My form validator returns the error in json and i can display it to user. The problem is that when it is successful it actually posts the data two times - first time from the ajax request and second time because i call form.submit() after ajax request is successful. Because i want to redirect the user after submit i would actually like only the second submit to reach the controller. This means i have to stop the ajax request after validation. My current workaround is that i have a line like this in my controller:
public function store(X $request)
{
if ($request->ajax()) {
return;
}
// only actual request reaches here
}
This works, but its not pretty. I don't like including this line in my controller. I would be happy if i could do something similar in my request validator, but I cant find a good way to return after validation from there. Any ideas how can i accomplish this?
You can try it like this:
<script>
function dosubmit(form) {
$.ajax({
async: false, // make ajax not async
url: $(form).attr('action'),
type: 'post',
data: $(form).serializeArray()
}).done(function (data) {
form.submit();
}).fail(function (data) {
alert('error');
});
return false;
}
</script>
and in controller just do it normally without this...
if ($request->ajax()) {
return;
}
And please give feedback if it works...I am also interested.
Your problem can be solved with some changed in javascript code. I think you're confused about what deferred.done() method will do. In your code, you're submitting your form twice.
Let me break down your js script, the done() method is used to do further actions after submitting your form (Please refer).
In your code, the first $.ajax actually submits your form to backend (here, if there are any errors from backend you can handle them in fail section). If the form submits successfully without any errors, then in done section you can define functions or actions about what you want to do after a successful form submission.
Instead of defining what to do after a successful form submission, you are resubmitting the same form again. So remove that part from js code and also the workaround you've done in your backend.
function dosubmit(form) {
$.ajax({
url: $(form).attr('action'),
type: 'post',
data: $(form).serializeArray()
}).done(function (data) {
// form.submit();
// handle successful form submission
}).fail(function (data) {
alert('error');
});
return false;
}

JQuery validation "remote" method response waiting message

I am using JQuery validation plugin "remote" method for Ajax based validation.
But I have to make some third party calls to verify data and it takes approx. 30 seconds.
So need to show some message to end user while data is getting processed by Ajax request. Can anyone help to achieve this?
You can see an example from below that i done:
jQuery Validate (Remote Method):
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: 'your-url-or-path-here.php',
cache: false,
dataType: 'POST', // Post, Get, Json, etc
data: {
field: $('.element').val()
}
beforeSend: function () {
$('.loading').css('display','none').show();
},
complete: function () {
$('.loading').hide();
}
}
}
}
});

jQuery .Validate() Remote sucess function and message

I need to validate an email field using the jQuery.Validate() plugin it has a "Remote" method which we have to post to a server and server needs to return true or false, Instead of using the traditional way(adding a function on the server to return true or false), I need to get json response from the server and on success run a function to decide where to return true or false...
Here is what the response from the server looks like (I'm using the Yii ajax form validation)
{
"zipcode":[
"Zipcode cannot be blank."
],
"email":[
"Email is already registered"
],
}
If email is listed on the array that means the validation had errors So I create a Remote validation rule like follows:
'email': {
required: true,
email: true,
remote:{
type:"POST",
url:url,
dataType:'json',
data:{'email':function(){
$('#email').val();
},ajax:'validate'},
success:function(resp){
$.each(resp,function(index,value){
if(index == "email")
return false;
});
}
}
},
But does not work, also I did not found anywhere where I can add the error message for remote validation, I would like to pass the array email value as the message...
You need to replace your success function with below function :
dataFilter: function (data) {
return 'false'; //Email not exist
return 'true'; //Email already exist
}
Please pass true/false value as a string.
For Display Message :
remote:{......},
messages:{email:'Please enter valid email', remote : "{0} is already exist"}
I think this will be help.

How to submit a form after confirming submit? jQuery, AJAX

Good day, I have a simple html page containing this form:
<form:form method="post" action="details" modelAttribute="code">
<form:input path="code"/>
<br/>
<input type="submit" value="Submit" />
</form:form>
When I press the Submit button I need to check whether there are some records in the database for given code using jQuery AJAX. If yes then popup jQuery UI dialog to ask user whether he really wants to display record details (because it's a paid service). If he confirms I need to submit the form. This is my script on the html page:
$(document).ready(function() {
// Bind an event handler to the submit event
$('form#code').submit( function() {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
success: function(result) {
if(result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function() {
// User confirmed, submit the form
$('form#code').submit();
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
When I press "Display details" button nothing happens. I think it is because I'm entering the same submit handler which returns false. How to solve it so that form submit is executed? Please advise.
Thank you in advance.
Vojtech
Change
$('form#code').submit();
to
$('form#code')[0].submit();
It will skip the jQuery onsubmit function.
Basic example: http://jsfiddle.net/4Ax6m/
There is one simple answer: Do not use <input type="submit" ... />.
You can instead use <button onlick="handler()">Submit</button>, where handler() is your function bound to the submit-event of the form in the above code. If your handler decides that the form should be submitted just submit it programmatically. Edit: Which is actually already in your code.
You'd need to wait for the .ajax to succeed since it is currently running in async mode.
So disable it using the async option on ajax. Documentation Here
ANSWER SPECIFICALLY FOR YOU
JS
$(document).ready(function () {
// Bind an event handler to the submit event
$('form#code').submit(function () {
// Check whether there are some records in the DB using AJAX
$.ajax({
url: 'getResultCount',
type: 'post',
dataType: 'html',
data: $("form#code").serialize(),
async: false,
success: function (result) {
if (result == 'null') {
$('div#results').html('<p>No records found for ' + $('input#code').val() + '.</p>');
//No Records found, submitting!!
return true;
} else {
// At leat one record was found so ask the user
$('#dialog-confirm').dialog({
resizable: false,
draggable: false,
height: 240,
width: 450,
modal: true,
buttons: {
"Display details": function () {
// User confirmed, submit the form
return true;
},
Cancel: function () {
//TODO: Don't think you need this line?
$(this).dialog("close");
//CANCEL!!!
return false;
}
}
});
//User skipped Dialog somehow...ignoring....DO NOT SUBMIT
return false;
}
}
});
});
});
Note: This will return true and false to continue the submit process to the server

How to remove AJAX from jQuery validation plugin function

This is going to be a stupid question but I have spent an inordinate amount of time trying to remove the AJAX part from the jQuery validation plugin function below but still have the validation work. Suffice to say I haven't succeeded.
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Choose a group."},
},
submitHandler: function(form) {
$('#results').html('Loading...');
$.post('', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
So yeah, I'm dumb. Can anyone help me out?
When you send the object back, send it as a JSON object.
Here's an example where we're going to use the serialized elements, conditionalize some data, and then send something back with our new page.
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
if(isset($name) && isset($email) && isset($phone)){
return json_encode(array('filled' => 'yes', 'loc' => 'newpage.php'));
}
?>
Then in the validator, we can parse data.loc to the window.location to mimic the redirect.
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
group: {required: true},
},
messages: {
group: {required: " Choose a group."},
},
submitHandler: function(form) {
$('#results').html('Loading...');
$.post('', $("#myform").serialize(), function(data) {
if(data.filled == 'yes'){
window.location = data.loc;
}
});
}
});
});
You just need to replace the submitHandler function!
submitHandler: function(form) {
$('#results').html('Loading...');
// $.post('', $("#myform").serialize(), function(data) {
// $('#results').html(data);
// });
}
And after calling .validate(), call the .valid() function on #myform this way:
$('#myform').valid();
Just make sure you are removing the default action of submit on the form by adding this:
<form onsubmit="if (!$(this).valid()) return false;">
Explanation: This doesn't submit the form when it is not valid and shows the errors. If the form is valid, this function submits as a normal form submit.
But why do you wanna do that? What else you wanna do?

Categories

Resources