This question already has answers here:
jQuery Validate remote method usage to check if username already exists
(2 answers)
Closed 5 years ago.
I have a form that that is already validated by jquery.validate.min.js, what I want is another validation method, ajax call to mysql to check if the email address is already in my DB. How do I merge the validations? I already played a little with the codes but can't figure it out.
My form: http://demos.creative-tim.com/wizard-demo-register?_ga=2.138099576.979789193.1518540669-1813170823.1518540669
My validation code:
$('document').ready(function() {
var email_state = false;
$('#email').on('blur', function() {
var email = $('#email').val();
if (email == '') {
email_state = false;
return;
}
$.ajax({
url: 'index.php',
type: 'post',
data: {
'email_check': 1,
'email': email,
},
success: function(response) {
if (response == 'taken') {
email_state = false;
alert('email is taken');
} else if (response == 'not_taken') {
email_state = true;
alert('email available');
}
}
});
});
});
The PHP who process the email check:
<?php
$db = mysqli_connect('localhost', 'user', 'pass', 'subscribers');
if (isset($_POST['email_check'])) {
$email = $_POST['email'];
$sql = "SELECT * FROM subscribers WHERE email='$email'";
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
echo "taken";
}else{
echo 'not_taken';
}
exit();
}
?>
Take a look at json_encode what you need to do is return a response (ex: true or false) to javascript from php (check this answer) .
Then check in the success js function the response, if it is true, then the email is already in the database, and alert the user, otherwise, submit the form with the email value.
There are two ways to accomplish this, 1) Make an ajax request for every keystroke on the email field $('#email-input').on('keyup')and once the response is false, enable the submit button via jquery $('#submit-button').prop('disabled', false) note that in your button html tag you should have the disabled property by default <input type="submit" id="submit-button" value="Submit" disabled /> and after the validation occurs you disable it, then it's going to be clickable and the user will be able to submit the form.
The problem is, that you're going to make a lot of ajax calls when the user types in the email address, and you don't want that, instead what you can do is to just make the request when the user submit the form (click on the submit button) and then prevent the default behaviour (sending a post request via form) for you to check via ajax if the email is already in use or not, if it is, do not submit the form and display a message, otherwise, submit the form.
<form id="form" action="http://foo.com" method="post">...</form>
$('#form').on('submit', function (ev) {
ev.preventDefault() // prevent default behaviour (making a post request)
// do your ajax call here to check the email availability
// if it's taken, do nothing and just display a message to the user
// otherwise, submit the form: $(this).submit()
})
Cheers.
Related
This question already has answers here:
How do I return a proper success/error message for JQuery .ajax() using PHP?
(8 answers)
Closed 2 years ago.
I am trying to clear the form files only if I get successful data submit call back. To do that I use PHP which echo "Your application submit successfully!"; and pass this message string back to Jquery which displays it into #response. But somehow it is not working. the if condition in jquery cannot detect the
Your application submit successfully! is there something that I am missing?
PHP:
if($query)
{
echo "Your application submit successfully!";
}
else
{
echo "<div class='alert alert-danger'>
<b><i class='fas fa-exclamation-triangle'></i> Something Went Wrong. Your data is not inserted!</b>
</div>";
}
Jquery:
success: function (data) {
if(data != null && data == "Your application submit successfully!"){
$('#enroll_form').trigger("reset"); //reset fields
} else {
$('#response').fadeIn().html(data); //this line render html+text
setTimeout(function(){
$('#response').fadeOut("slow");
}, 7000);
}
Instead of checking for the whole text I would check for just a chunk of that sentence:
if (data != null && data.toLowerCase().includes("successfully") {
Otherwise you are more likely to make a typo and your code is more likely to fail.
And consider showing always the response, not in the else:
if (data != null && data.toLowerCase().includes("successfully") {
$('#enroll_form').trigger("reset");
}
$('#response').fadeIn().html(data);
setTimeout(function() {
$('#response').fadeOut("slow");
}, 6000);
I m validating a data by clicking the submit button and then again loading the views. I want just to show the errors on the page before loading the controller. Its is not a form validation. it is just a data validiation.
I think you can do the validation using AJAX.
in view page
<script type="text/javascript">
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function(){
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(email_val)){
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/user/email_check", {
email: email_val
}, function(response){
$('#loading').hide();
$('#message').html('').html(response.message).show().delay(4000).fadeOut();
});
return false;
}
});
});
</script>
in controller function
public function email_check()
{
// allow only Ajax request
if($this->input->is_ajax_request()) {
// grab the email value from the post variable.
$email = $this->input->post('email');
// check in database - table name : tbl_users , Field name in the table : email
if(!$this->form_validation->is_unique($email, 'tbl_users.email')) {
// set the json object as output
$this->output->set_content_type('application/json')->set_output(json_encode(array('message' => 'The email is already taken, choose another one')));
}
}
}
The registration form must be Ajax , to send data to the server via Ajax . When you click the submit appears a spinning gear . If the registration was successful then a message " You have successfully registered " If not occur with the error message " Invalid Email Address " or " username already exists " , etc.
We include the jQuery library page
JQuery add an event that no longer do submit the form
Added an event with jQuery , when making submit to execute ajax
Depending on the message came to Ajax , whether to show success or failure
This is all greatly simplified but on the javascript side, you could do this:
var params = {"email": $("input#email")
$.post(yourserver.php, params, validate, "json")
function validate(response) {
if (response.success) {
console.log("Allgood")
} else {
console.log(response.message)
}
}
and on the php server side, your server.php could look like this:
<?
if ( $_REQUEST["email"] ) {
$response = array("success" => true)
} else {
$response = array("success" => false, "message" => "Missing email");
}
echo json_encode($response);
?>
function success(answer) {
$(".loader").hide(); // Hide loader element
// Back-end side must return 3 numbers, where is
// 1 - success
// 2 - invalid email
// 3 - username already exists
if (answer === 1) { // if returned code "1" then output message of success
console.log("You have successfully registered");
} else if (answer === 2) { // if returned code "2" then output message of invalid email
console.log("Invalid Email Address");
} else if (answer === 3) { // if returned code "3" then output message of username already exists
console.log("Username already exists");
}
function loading() {
$(".loader").show(); // Show loader element
}
$("#submit").on("submit", function() {
$.ajax({
url: ("/handler"), // url address of your handler
type: "POST",
data: ({
email: $("input#email"),
login: $("input#login"),
password: $("input#password")})
beforeSend: loading, // should call loading() without arguments
success: success, // should call success(answer) where answer is result which returned your server
});
});
I am developing a website for practice, and I would like to know how to use JS to notify the user that the username he picked is already in use, all works fine, if my function(check_username) returns false, the user succesfully registers himself into the site, otherwise the register won't happen.
When the user can't register I would like to know how can I notify the user with a js script.
<?php
//database includes
include_once('../config/init.php');
include_once('../database/users.php');
if(!check_username($_POST['username'])) {
insertUser($_POST['name'], $_POST['username'], $_POST['email'], $_POST['pass']);
}
else header('Location: ../index.php');
?>
One way would be to change your redirect on failure to a javascript message
else
{
echo "<script>alert('Username already exists');</script>";
}
That's a very trivial example to get you started since you mentioned you're learning JS. You can build a lot of improvements on that.
You can set the returns into a javascript variable and use it to display message if the user is not registered.
var x = <?php echo check_username($_POST['username']); ?>;
if(x) {
alert("You are not registered");
}
You can use php ajax for a live notification to users.
<script>
$(document).ready(function() {
$("#InputFieldID").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
//Getting value of input field.
var username = $(this).val();
//Check only if the username characters are above 4
if(username.length >= 4){
$("#IndicatorDivID").html('<p style="color:#ffbf25;">Checking..!</p>');
$.ajax({
type: 'POST',
url: 'check_username.php',
data: {"username": username},
dataType: 'json',
success: function (data) {
if(data.response=='true')
alert("Already Exist");
}
});
}
});
});
//Username Checker
</script>
The result fo check_username.php must be in json format.
eg: {"response":"false"}
I amc creating A Login script with php and javascript.
What I want to do is log the user in without the page refresh which I have archived so far, With some help from Stack Flow users, I am fairly good with PHP but new to the Javascript client side.
Anyway, When the user enters the correct data and the session gets started how do I get it to call the fade out function?
Heres the PHP Side
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
echo "
Yes, Now we can start the session right here, when your ready.
<script>
$('#field').fadeOut();
</script>";
} else {
echo "The username or password you entered is incorrect";
}
} else {
echo "<b>Blank Fields</b> <br>
You must enter A Username/Password Combination";
}
?>
Incase yous need it, there is the client side aswill (modified by some users to make the functionality better)
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Since PHP is Server Side and Java Script controls the Client side, Probably the best way to do or call it is this way, But its worth A ask anyway.
Besides this everything is working out well.
If you want you can help change the way loading data is coded/works, But the functionality is working perfectly so theres not much need.
The ajax success method needs to check the response from the server to see if login was successful and then take the appropriate action:
// php
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
echo 'correct';
} else {
echo 'The username or password you entered is incorrect';
}
// js
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
if (data === 'correct') {
$('#field').fadeOut();
} else {
$('#content').html(data);
}
}
});
}
Returning JSON instead of raw HTML is much more flexible. Quick example:
PHP Side
<?php
require "../core/database.php";
$json = array('success' => false, 'error' => null);
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
$json['success'] = true;
}
else {
$json['error'] = "The username or password you entered is incorrect";
}
} else {
$json['error'] = "<b>Blank Fields</b> <br>You must enter A Username/Password Combination";
}
echo json_encode($json);
Your AJAX function:
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
var loginResult = JSON.parse(data);
if(loginResult.success){
//Login successful - fade out whatever form or fields
//that you want to
$('#field').fadeOut();
} else{
//Add error message to an error div or whatever
$('#error').html(loginResult.error);
}
}
});
}
I'll start by saying that your PHP should be using the newer mysqli_* functions or the PDO object for all of your database queries. Further, you should be using prepared statements which will safeguard you against SQL injection attacks.
Another thing to note is that in a PHP file that is not going to output anything to the browser, or in other words, is just going to run some code, you don't need a closing tag. In fact, you don't want a closing tag. That is because anything after the closing tag will get sent to the browser, which will get included in the response of your AJAX success function. That includes things like spaces and new lines.
Now, on to your PHP. You are going to want to output some JSON so that you can check for success or failure in your AJAX.
PHP
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
//Create an array to represent our JSON data.
$json = array(
"successCode" => 0
);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//echo "Yes, Now we can start the session right here, when your ready."
$json['successCode'] = 0;
} else {
//echo "The username or password you entered is incorrect";
$json['successCode'] = 1;
}
} else {
//echo "<b>Blank Fields</b> <br>
//You must enter A Username/Password Combination";
$json['successCode'] = 2;
}
//Set that our content type is JSON
header("Content-type: application/json");
echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.
In our PHP, we have created a $json array which will story the successCode that we will be responding to the client. This will tell the client if the login was a success or failure, and even what type of failure occurred. It will then be up to the client to decide how to display that success or failure to the user. This allows multiple applications to use the same server side source, but display the errors differently if desired.
At the end of the PHP, we have set the header Content-type to specify that we are sending back application/json to the client. Then, we encode the PHP array as JSON, and output it to the response.
jQuery/Javascript
//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
"Yes, Now we can start the session right here, when your ready.",
"The username or password you entered is incorrect",
"<b>Blank Fields</b><br />You must enter A Username/Password Combination"
];
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
//First, make sure that data and data.successCode are defined.
if (data && data.successCode) {
//Here, you are getting back the JSON data from the login call.
$('#content').html(errorMessages[data.successCode]);
//If the successCode is 0, which means it was successful, then we want to fade out the #field div.
if (data.successCode == 0) {
$('#field').fadeOut();
}
} else {
//There must've been a server error. You'd handle that here.
}
}
});
}
Why put the error messages on the client instead of the server? Because it allows you to easily change how the error messages are displayed, without having to touch the server side code. The server just outputs an error code, and the client decides how to handle that code.
The Javascript array, errorMessages, defines the error messages corresponding to their index in the array. The error message at index 0 would correspond to successCode = 0, and so on. If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code.