Performing ajax Checks Before Form Sumbit via Javascript - javascript

I have a simple form which is used to sign up a new user . I want to prevent users from submitting the same email id again . So before the form gets submitted , I want to do an Ajax check if the email id exists or not . If the email id exists , I alert the user . If it doesnt , I let the form be submitted .
$("#sign_in_form").submit(function(event){
event.preventDefault();
$.post("http://xyz.com/check_if_user_exists", {
email : $("#contact_person_email").val()
}).done(function(data) {
var res = parseInt(data);
if(res==1){
//Email Exists
alert("Email exists . Please use different email " );
return false; //----------------------------1)
}else{
//Email doesnt exist
return true; //--------------------------- 2)
}
});
//end of function
});
The problem with this code is due to async nature of Javascript , the function ends even before the result is returned from the ajax post statement . Hence the return false or return true statement at 1) and 2) have no effect . Whats the correct way to handle this ?

Submit form using js native event if check is valid:
$("#sign_in_form").submit(function (event) {
event.preventDefault();
$.post("http://xyz.com/check_if_user_exists", {
email: $("#contact_person_email").val()
}).done(function (data) {
var res = parseInt(data);
if (res == 1) {
//Email Exists
alert("Email exists . Please use different email ");
} else {
document.getElementById('sign_in_form').submit();
}
});
//end of function
});

Related

How to check unique username before form submission

I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.

Return Single Response using PHP_SELF

I'm using $_SERVER['PHP_SELF'] to run a function because of the way it's included and called within my plugin page I can't directly call the functions.php file, so what I'm trying to do now is work on the registration script, the problem is my returns can't be utlized the way I would like. For instance.
public function CheckUserName() {
$query = <<<SQL
SELECT id
FROM {$this->tprefix}accounts
WHERE username = :posteduser
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':posteduser' => $_POST['username'],
));
if($resource->rowCount() == 0 ) {
//Self Continue to run checks
}
else {
echo "1";
}
}
is my check to make sure that a username isn't already taken, whereas two will be my response echoed if the email is already in use. My Ajax is
$(function() {
$("#register_").submit(function(event) {
event.preventDefault();
var username = $("#username").val();
if(username == "") { $("#unameerror").html("Username is Required"); }
$.ajax({
type: "POST",
url: $("#register_").attr("action"),
data: $("#register_").serialize(),
success: function(data) {
if(data==1) { alert("Username is taken. Please choose another!" };
if(data==2) { alert("Email already registered. Please select lost password
if you have forgotten your password" };
if(data==0) { alert("Account Created!") }; //0 is returned after all checks passed and scripts executed
},
error: function() {
alert("Something isn't right");
}
});
});
});
My issue is since it's running from PHP_SELF it's putting out all information(IE <html><title>reg script</title><body><form id = "reg"></form></body><html>
The best way I can think to put this is how can I parse all my data return to simply return the script code?
This worked for my framework. Since everything is included into the index.php file and then just pulled through variables as includes it's always the index.php file
which is currently
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once(dirname(__file__).'/config.php');
require_once(dirname(__file__).'/directives.php');
LoadClasses();
$Theme->Load(ACTIVETHEME);
I simply changed the bottom part to
if(isset($_POST['process'])) {
}
else {
$Theme->Load(ACTIVETHEME);
}
Now it has no problem loading my pages, but when I execute a form with process input ( IE <input type="hidden" name="process" id="process" value="register"> )
It now loads the page if no form is executed, but since I want all plugins to run through ajax it works great with that addition if a process was posted then it only returns the php scripts data.

Use AJAX and PHP to "Alert" the user if the username exists on the same page?

I have found many AJAX scripts that do a live check on if the username exists in a MySQL database. For example, most will maybe show a green check image if it does not exist or a red x if it does already exist.
I am interested in a slightly different method for this form.
Users fill out a 10 question quiz and then are taken to a user registration form. I only want to insert the user's answers into the database if they complete the quiz.
Currently, if a user enters a username or email that already exists, they will receive an error on the next page and be told to be go back only to find that the form has been reset.
That is why I want the information validated all on the same page.
Upon clicking the submit button, a javascript function is called that verifies a few things such as if the user has entered a date of birth, has not left a form blank, if passwords match, etc.
It returns false if any of the criteria is not met so that the form does move to the next page unless all of the functions return true.
Here is what it looks like.
function checkForm() {
if (checkUser() && checkPassword() && checkMonth() && checkDay() && checkAddress() && checkYear()) {
document.getElementById("quizForm").method="post";
document.getElementById("quizForm").action="register.php";
}
else {
return false;
}
}
I am interested in creating a username/email check function that uses ajax to access a php page that searches the database and returns true or false to javascript on if the username/email exists in the database.
That way, I can just use the old javascript alert to say if a username/email exists and then return false so that the form is not submit.
This is an example of how I am writing the functions for this:
function checkPassword() {
var pass1 = document.getElementById("pass").value;
var pass2 = document.getElementById("c_pass").value;
var pass1l = pass1.length;
if (pass1l < 5) {
alert("Please create a password that is longer than 5 characters.");
return false;
}
else {
if (pass1 != pass2) {
alert("Your passwords do not match.");
return false;
}
else {
return true;
}
}
}
Can anyone point me in the right direction for this? I have been searching around but have not found anything that is this specific.
Thank you.
You could AJAX Post on change event of the <input> where the user enters the username. Consider the example below I quickly put together. It assumes you have the database table users with columns id and username. It also assumes you have a file check.php connecting to this database table with a MySQLi connection in the variable $mysqli. When the input changes, it will call check.php, with the only data being the username entered. Depending on the response, it will update <span id="info">.
HTML:
<input id="username" type="text" /><span id="info">Exists/Does not exist</span>
Javascript(jQuery):
$(function() {
$("#username").on("change", function() {
var data = "user="+$("#username").val();
$.ajax({
type: 'POST',
url: 'check.php',
data: data,
dataType: 'json',
success: function(r)
{
if(r=="1")
{
//Exists
$("#info").html("Username already exists");
}else{
//Doesn't exist
$("#info").html("Username available!");
}
}
});
});
});
PHP(check.php):
$user = $_POST['user'];
if($stmt = $mysqli->prepare("SELECT id FROM users WHERE username = ?"))
{
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id);
$stmt->fetch();
if($stmt->num_rows>0)
{
echo "1";
}else{
echo "0";
}
}
I'm using similar functionality on my current project, and it works fine. Especially with local files as response time is improved!
(Reserved for typos, was in a rush-ish)
Hope this helped.

Prevent form submission in jQuery by ID

I am using jQuery Ajax function to check the existence of user email in the database on jquery change function. in Ajax responsive there are two possibilities that either user email exists or not. If it exists it shows the error message. Now I wanted to prevent the form from submitting if the Ajax responsive is false
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
//prevent form here
}
else {
// else condition goes here
}
});
You can put a global variable like
emailValidated = false
And on
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
emailValidated = false;
}
else {
// else condition goes here
emailValidated = true;
}
});
After that on form submit check the value of the emailValidated variable.
$(form).submit(function(){
if(emailValidated) {
this.submit();
}
else {
return false;
}
})
Use e.preventDefault() to prevent form from submission.
jQuery("#userEmail").change(function(e){
if(result == 'False'){
e.preventDefault();
}
else {
}
});
Do something like this:
var result;
$.ajax({
url: url,
// Put all the other configuration here
success: function(data){
if(data == something) // replace something with the server response
result = true; // Means that the user cannot submit the form
},
});
$('#formID').submit(function(){
if(result){
alert('Email already exists.');
return false;
}
});
Steps are like :
get the email value passed by the user from input field in Jquery.
The POST that data to your PHP query file and get the response data on "success: function(data)" function of jquery.
Display that data data on the page..
Check below link for a reference.
http://www.sitepoint.com/jquery-ajax-validation-remote-rule/
You need use the submit event handler:
jQuery("#userEmail").closest("form").submit(function(event){
var $email = jQuery("#userEmail", this);
//the email field is not `this`, but `$email` now.
//your code goes here
if(result == 'False'){
event.preventDefault();
}
else {
// else condition goes here
}
});
You can still attach other behaviours to the change event if needed. The important thing is to do event.preventDefault() on the submit event.

$posts jquery submits my form

<script type="text/javascript">
function claim()
{
var c = confirm('You sure?');
if(c)
{
var password=prompt("Please mention pw","");
if (password!=null && password!="")
{
$.post("/claim/<?php echo $refnr; ?>", { partner_pwd: password },
function(data) {
alert(data);
if(data == '1')
{
return true;
}else{
return false;
}
});
}else{
return false;
}
}else{
return false;
}
}
</script>
When testing I get to the Please mention pw, after i entered and press OK it submits my form, instead of making the $.post and only submit my form if data == '1' (return true)
claim() is called at my submit button;
<input type="submit" name="submit" onclick="return claim()"; value="Submit" />
I tried alert debugging and it was true like i thought it automatically submits when it reads the $.post(), I only wish it to submit (by returning true) if the data is 1.
Well, if you put a form in a website, it's goal is to submit the form.
http://api.jquery.com/submit/ (scroll down to the very last example starting with Example: If you'd like to prevent forms from being submitted unless a flag variable is set, try:)
As stated in the link above, you should change form's action instead of some page and do something like action="javascript:claim()". I think that should work.
The return true and return false inside of your $.post request do nothing but return out of that callback. It does not prevent the form from submitting. Instead, try preventing the submit completely and then triggering it if you want the submit to happen.
function claim() {
var c = confirm('You sure?');
if (!c) {
return false;
}
var password = prompt("Please mention pw", "");
if (password != null && password != "") {
$.post("/claim/<?php echo $refnr; ?>", {
partner_pwd: password
}, function(data) {
alert(data);
if (data == '1') {
$("#myform").submit();
}
});
}
return false;
}​
Note how we always return false out of that function regardless of the validity. If it is valid, we trigger the form's submit event directly.
Your onclick method on the submit it's not working because the form will be submitted eitherway.
You should for example set a listener on the onsubmit(); event on the form
or another solution is on the put the onsubmit attribute with your javascript function in it and submit the form from your javascript with the $('#form').submit(); function.

Categories

Resources