Checking for duplicate username - javascript

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();
}
});
}

Related

How to add php file inside the confirm() function from JS

So, I want delete records from database using confirm() function, inside this alert should been shown what will be deleted when "OK" button will be clicked. To sum up, I just want to put php file inside the confirm().
function deleteGame() {
if(confirm('Do you want delete this?')){
$(".deleteButtton").load('deleteGame.php?id=' + $(".deleteButtton").data("id"));
}
}
Hmmm, I guess you must try AJAX Request for deleting record, check the following code for reference.
if (confirm("Do you want this to be deleted?")){
//HERE YOU CAN SHOW SOME PROGRESS WHILE THE JS IS REQUESTING PHP TO DELETE FILE
$.get(
"deleteGame.php",
{
id: $(".deleteButtton").data("id")
},
function (result){
/*ASSUMING THAT YOUR PHP FILE WILL RETURN "deleted" AFTER DELETING RECORD.*/
if (result === "deleted"){
alert('DELETED!); //SOME ACTION AFTER DELETING.
}else{
alert('ERROR'); //SOME ACTION FOR ERROR
}
}
);
}
I WOULD SUGGEST USING POST METHOD INSTEAD OF GET METHOD FOR SECURITY ISSUES.
Whenever you want to run a php function similar to deletion of a db record you have pretty much 2 options.
Open a new page in your browser or redirect a user to a new page.
Open a new page "silently" in a background without user knowing it.
The first option is ok, if you dont mind showing user a different page. For example if you wanted to show a page that would have text in it "Thank you for deleting this record". Achieving this would be really simple, you could just use javascript redirect like this:
if(confirm('Do you want delete this?')){
window.location.href = 'deleteGame.php?id=' + $(".deleteButtton").data("id");
}
However in some cases you want to run the php function without leaving the current page. In cases like this you should use AJAX. My simplification: Using AJAX you can open the php file in the background, run the function and once its done you can run javascript to inform a user the operation was successful.
To achieve this you would need to add the AJAX call like this:
if(confirm('Do you want delete this?')){
$.ajax({
url: "deleteGame.php",
method: "POST",
data: { id: $(".deleteButtton").data("id")},
success: function (result) {
alert("The operation was successful")
}
});
}
And in your deleteGame.php file you would need to listen to incoming data:
$id = $_POST['id'];
//Your own script to delete the record. You can access the record id by $id

Contact Form 7 not redirecting upon email sent

I have a form that I am trying to have redirect to http://www.example.com upon successfully sending an email. I have tried different approaches including on_sent_ok in the additional settings as well as
if(jQuery('.wpcf7-mail-sent-ok').length > 0)
window.location.replace("http://stackoverflow.com");
in my JavaScript, but that does not seem to work as well.
Edit: I forgot to mention that upon the user clicking submit, I do a prevent default in order to do some calculations and generate a PDF. Once it is all done I do
$("form.wpcf7-form").unbind('submit').submit();
to allow the submission to happen. Could this be causing any issues with the redirection?
Contact Form 7 made a ajax call. After success the element is inserted. Then you can check if element exist:
jQuery(document).ajaxComplete(function() {
if (jQuery('.wpcf7-mail-sent-ok').length) {
alert(1);
//window.location.replace("http://stackoverflow.com");
}
});
Well, maybe I'm writing late, but this code will definitelly will do the job. (If you're working in wordpress). I'm using it so far and it's working normally.
Remember to place this code at your functions's file and as final note remember that you must use one or the other, not both...!
add_action('wp_head', 'RedirectsCF7');
// Start of function.
function RedirectsCF7() {
if(is_page("contact-page-or-whatever-page-name-is")) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
// Or simply add this code to all pages, like this.
if(!is_admin()) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
Reference here

Page redirect in jQuery fails randomly. Race condition?

Elaborating on an example from the very good post by Felix Kling I wrote some jQuery code to authenticate a user. If the authentication is successful the window.location object should be assigned/replaced to a new URL.
The redirection occasionally fails, even though the user is authenticated correctly: based on the values of sessionStorage('Auth') the looks of the menus for an authenticated user are modified by some other JS code, so I know when the credentials were entered correctly.
Here is my code.
$(document).ready(function() {
$('#submit').click(function() {
var webServiceHref = window.location.href;
var webServicePath = webServiceHref.slice(0,webServiceHref.lastIndexOf("/"));
var serviceUrl = webServicePath + "/login.php";
$.post(serviceUrl,
{
Email: $("#Email").val(),
Password: $("#Password").val()
}).done(function(data, status) {
var json = JSON.parse(data);
if (json.valid == true){
sessionStorage.setItem('Auth', true);
sessionStorage.setItem('FirstName', json.FirstName);
sessionStorage.setItem('Email', json.Email);
$("#messageLine").val("Authentication succeded");
$(location).attr('href', webServicePath + "/welcome.html");
// window.location.href = webServicePath + "/welcome.html";
} else {
sessionStorage.clear();
$("#messageLine").val("Incorrect Username or Password");
}
});
}); // click
}); // ready
This behavior does not depend from the way the redirection is called:
I left in my code, commented out, some of the JS and jQuery
combinations of methods (window.location.assign, window.location.replace etc.) suggested in numerous posts on SO.
I have even tried .reload() without success.
In Chrome inspector I can even see the callback statements being executed, the assignment of the new URL being made, but when the function returns the window object sometimes does not change, and sometimes ... it does.
Perhaps the assignment of the URL is queued after other event which causes the original login.html page to be reloaded?
What am I missing? Am I using the deferred object incorrectly?
Thank you in advance for your help.
If your "#submit" element is actually submitting a form (e.g. it is an input of type "submit" within a form), that could cancel the page redirection. E.g. when no action is specified on the form, it just reloads the same page, preventing your modification of window.location.href from having any effect.
See also that post: javascript redirect not working anyway
You have 3 easy possible solutions:
Turn your element/button into a normal one (not a submit).
Prevent the element/button from submitting the form (function (event) { event.preventDefault(); /* rest of your code */}).
Attach your main callback on the form submit event. The user is then able to trigger the action by hitting "Enter", not just by clicking on the submit button.

JS/JQuery/PHP - How to echo errors on form validate failure, and jump to div on success?

I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.

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