Trouble updating a <div> after successful validation using jQuery Validation plug-in - javascript

I am validating a form using the jQuery Validation plug-in, and I'm having some trouble updating a <div> with the status once the form is submitted (called using submitHandler). Once the user clicks to submit the form, it should update the #inviteStatus element with a status ("Adding user"). Then, once the response is received from the server (1-2 seconds) it should update #inviteStatus again with a result ("Success" or "Fail"). However, my script is jumping directly to the latter update ("Success" or "Fail"), and skipping the first "Adding user" update.
http://jsfiddle.net/bhall7x/Mf7sq/4/
I tried inserting a delay(5000); after the first <div> update, but the script seems to just stop at that point, and never continues on to the second result update message.
Any ideas why this is happening? Thanks!
UPDATE: I've created an updated Fiddle that has the actual code that I'm using. I can't get the .ajax() query to actually work on JS Fiddle, but this way you can see what I'm trying to accomplish. Basically, I'd like to first update #inviteStatus, show it, then
update it with the results of my .ajax() query. Here's the code I'm using in the submitHandler of the jQuery Validation plug-in after the form is successfully validated:
// form successfully validated, provide user notification
$("#inviteStatus").html("<div class=\"alert alert-info\">Adding user</div>");
$("#inviteStatus").show(500);
// get form values
var postData = $(form).serializeArray();
// submit form
$.ajax({
type : "POST",
data : postData,
async : false,
cache : false,
url : "inviteScript.php",
success: function(result) {
// Provide the results of the ajax call
$("#friendInviteStatus").html(result);
$("#friendInviteStatus").show(500).delay(5000).hide(500);
}
});

You need to add an anonymous function to the show() call instead of altering the html on a different line.
$("#inviteStatus").show(500);
// submit form here via ajax() call
$("#inviteStatus").html("<div class=\"alert alert-success\">Success!</div>");
Should be
$("#inviteStatus").show(500,function() {
// submit form here via ajax() call
$("#inviteStatus").html("<div class=\"alert alert-success\">Success!</div>");
});
http://jsfiddle.net/Mf7sq/7/

it is working fine, to simulate the ajax you need to give a delay
// Form actions
$("#addForm").validate({
debug: true,
rules: {
invitee: "required"
},
messages: {
invitee: "Please enter a username"
},
submitHandler: function (form) {
$("#inviteStatus").html("<div class=\"alert alert-info\">Adding user</div>");
$("#inviteStatus").show(500);
// submit form here via ajax() call
//simulate the ajx call
setTimeout(function () {
$("#inviteStatus").html("<div class=\"alert alert-success\">Success!</div>");
$("#inviteStatus").show(500).delay(5000).hide(500);
}, 2000)
}
});
Demo: Fiddle
Another slightly modified version is http://jsfiddle.net/arunpjohny/9jLb5/2/ - It is not recommended since it delays sending the ajax request till the message is completely shown

I was actually able to get this to work by removing the async:false on the .ajax() call.

Related

Google reCAPTCHA fail for second time submit

I implement the reCAPTCHA in this tutorial,
https://codeforgeek.com/2014/12/google-recaptcha-tutorial/
which work well for the first time submit. The problems I have are:
I send the captcha with other form data e.g. username , email etc.... so if captcha is correct but other not , the user will send it again, but the second time it return "{ "success": false }"
if I idle it for ~2 min , it will session expire and if I select the box it pop up alert and warning something like " can not refresh : invalid parameter", and I can not select the box again
How to fix those problem? Thanks a lot.
Google reCAPTCHA gives these two functions: I always use this in all my AJAX powered forms.
grecaptcha.getResponse()
grecaptcha.reset();
For both of your problems, use the second function whenever you need in your JavaScript code.
Remember this works if you have only one CAPTCHA in your page. If you have more than two CAPTCHAs use their IDs as explained in Google Docs
https://developers.google.com/recaptcha/docs/display#js_api
Those who have the same problem and meet this topic during research;
If you experience problem when you render the captcha automatically, try to render it explicitly. In order to do this, add following code inside body tag.
<script src="https://www.google.com/recaptcha/api.js?onload=recaptchaCallback&render=explicit&hl=tr" async defer></script>
var recaptchaCallback = function () {
// alert("grecaptcha is ready!");
grecaptcha.render("YOUR HTML DIV ID", {
'sitekey': 'YOUR SITE KEY',
});
};
I'm using AJAX to check registration form and get response. So I have added reset function to my AJAX response.
$('#frmRegistration').submit(function () {
$.ajax({
url: "_ajax/_ajaxRegistration.php",
type: "POST",
data: $('#frmRegistration').serialize(),
success: function (reply) {
$('#resultRegistration').html(reply);
grecaptcha.reset();
}
});
});
Reference Google reCaptcha explicit render.

Checking for duplicate username

I am doing a registration page, for my mobile app, and want to check for duplicate usernames entered by the user/client
I have a button on the page that when clicked, checks availability of the username. However I would like to also incorporate that automatically, if not already done so, when the client clicks submit/go to step 3,
I want to perform the check for duplicate usernames using Ajax and if there exists a duplicate, then refresh the SAME page with the error message for duplication, else proceed to step 3.
In my HTML file I have some js that does the following:
$("#check-username").click(function() {
(...this works as I am able to click the CHECK button
and see if the username exists)
I have another js file, that is sourced in my HTML that does the following:
submitHandler : function() {
$("#reg1").hide();
$("span#step").html("2");
$("#check-username").click;
$("#reg3").show();
scrollTop();
}
When I click on Go to next step which is reg3, It does not do the validation for check-username. Is my method/syntax for calling check-username correct?
$("#check-username").click;
^^----- Missing Braces
supposed to be
$("#check-username").click();
The problem is you need to go to step 3 only after the validation ajax request returns from the server. You also are going to need to look at the response from the server to see if it's a duplicate. For example:
$("#check-username").click(function() {
validateUser();
});
function validateUser(){
return $.ajax({
url: '/path/to/validate'
});
}
And your submit handler stuff:
submitHandler : function() {
$("#reg1").hide();
$("span#step").html("2");
validateUser()
.done(function(r){
//for example...
if(r.isValidUser){
$("#reg3").show();
scrollTop();
}
});
}

jQuery: Persisting form values before serialize?

I am using jQuery serialize() function to collect data in a form and submit to server using jQuery Ajax "post" method, like this: var params = jQuery('#mainContent form').serialize();.
The strange thing I saw is the serialized data from my form contains old data. It means, all of my changes in form (input to text-field, select on combo-box) is not stored to DOM, so when jQuery call serialize(), it collect the old data which appeared before I change the form. I tried to inspect to each element in that form and call .val(), it still showed the old values.
So how can I persist all my changes to form, that the serialize() method can build the string with newest data I entered?
Here is my snippet code, I called serialize() inside submit handler
jQuery('.myFormDiv input.submit').click(function() {
// Do something
// Collect data in form
var params = jQuery('#mainContent form').serialize();
// Submit to server
jQuery.post(url, params, successHandler);
}
Thank you so much.
When are you calling serialize? it should be $('form').submit( [here] ); It sounds like it's being called on page load, before you enter values into the fields, then being used after.
EDIT:
using the submit event instead of on click will catch someone hitting enter in a text field.
jQuery('#mainContent form').submit(function() {
// Collect data in form
var params = jQuery(this).serialize();
// Submit to server
jQuery.post(url, params, successHandler);
}
*the above code assume url is define and successHandler is a function.

Sending a JSON string as a parameter to an action

I have a button on my Ruby on Rails view file.
Firstly when the button is clicked an Ajax call is made which in response gives a JSON string. So far I have accomplished this task.
Here is where I am stuck: The button also redirects me to another action of the same controller. Now I want to send the JSON string received by JavaScript as a parameter to that action.
Is there any way around this?
Your ajax call should look something like this:
... doing stuff before ...
$.ajax(
url:'url-to-script',
success: function(data) {
var json = JSON.parse(data);
$('#hidden-field').val(json); // set a hidden field in your form
$('#from-id').submit();
}
);
$('#submit-button').attr('disabled', 'true'); // disable the button
// set some spinny animation to notify the user that you are waiting.
// time out after a while if you don't get a response
... doing stuff after ...
Basically we fire off the ajax event, disable the button and notify the user you are waiting. When the call returns, your callback method submits the form to rails. You can also set a time out for the ajax call and let the user resubmit if necessary. You can handle the error case however you like.

Validating and Submitting a form using Javascript + Ajax

Here's what I'm trying to do.
When the 'Submit' form is clicked on my form, a javascript function will loop through all the fields of the form.
For each field a function will be called which would return true/false to indicate if it was filled in correctly or not.
If a false is returned, it shows an error message next to that field.
If all fields are correct, it submits the form. If not, it doesn't submit.
Here's the tricky part. While most of the validation is being done via javascript, the username and email need to be validated via ajax to see if the username/email is already in use or not.
The structure i'm currently using for this ajax function is something similar to this:
function validateSomething()
{
var valid;
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
return valid/
}
But that currently doesn't work.
What can I do to make it work, i.e can I stop the validateSomething() function from returning a value until its set to true/false by the inner function?
Would something like this work:
function validateSomething()
{
var valid="unset";
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
//Loop without returning until valid is set to true or false
while (valid=='unset')
{
//Do nothing?
}
return valid/
}
You can force the ajax-call to wait with async: false.
Like this using jquery:
function validateSomething() {
var valid;
$.ajax({
url: "something.php",
data: {x: y},
type: "GET",
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
valid= response.valid;
}
});
return valid;
}
However, the big win when using AJAX is that it is asynchronous. This synchronous call might lock up the browser while it is waiting for the server.
You probably don't want to. (Or more appropriately, "Go for it, but be careful when doing so.")
Validating via AJAX is hip and slick and awesome. But it is -not- a substitute for validating server-side. And AJAx validation is -not- server-side validation. I can take the return of your function that says false and flip it to true and submit the form happily, even though you checked to make sure the username wasn't taken 'on the server'. Javascript runs on the client and can't be trusted.
Any validation you do via an AJAX call must be re-done on the server when you actually submit the form.
If you do that, then yea, AJAX validation is, again, hip and slick and awesome. So go for it. To submit a form using javascript (e.g. in the AJAX call-back handler function) you would say:
if(formwasValid)
{
document.getElementById('idOfForm').submit();
$('#idOfForm').submit(); //jQuery
}
else
{
alert('Invalid text');
}
I stopped doing extensive form validation on the client side as the code has to be duplicated on the server side anyway.
On the client-side, I just do some basic syntax checking of fields via regular expressions. These checks will be immediately triggered when the user starts typing, but they just give a visual notice as to when something went wrong (red border, different background color, a red 'X' next to the field...).
I don't prevent the user from submitting even invalid forms: Then, the server-side code with it's more detailed checks gets to work, which can easily restructure the form to separate valid from invalid fields and generate in-depth explanations as to why a check failed.

Categories