I have an issue im stuck for 3 days. Im trying to check in DB if the email the user is entering is already registered and avoid registering in duplicate. But this doesn't seem to work fine
here is my code:
This is in the HTML
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "")
{
$("#msg").html("");
$("#Submit").attr("disabled", true);
}
else
{
$("#msg").html("Verificando, espere...");
$.ajax({
url: "check_availability.php",
data: {Email: uname},
type: "POST",
success: function(data) {
if(data.status == true) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#Submit").attr("disabled", true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#Submit").attr("disabled", false);
}
}
});
}
});
});
</script>
<right><form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required><div id="msg" class="form-group"></div>
</form></right>
this is the check_availability.php
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["cf_email"]) && $_POST['cf_email'] != '')
{
$response = array();
$cfmail = mysqli_real_escape_string($con,$_POST['cf_email']);
$sql = "select Email from Bares where Email='".$cfmail."'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'email already exists.';
}
else
{
$response['status'] = true;
$response['msg'] = 'email is available.';
}
echo json_encode($response);
}
?>
it doesn't matter which email i introduce in the textfield because always says its available even if the email is registered already in the database
In your JS you're processing a string, not an object. You need to parse it:
success: function(data) {
dataObj = JSON.parse(data);
if(dataObj.status == true) {
....
This is an Example with mysqli OOP try it will work without Problem:
PHP:
<?php $mysqli=new mysqli($host, $user, $pass, $db); mysqli_set_charset($mysqli,'utf8');
if (!empty($_POST['cf_email'])){
extract($_POST);
$sql=$mysqli->query("select Email from Bares where Email='".$cf_email."'");
if($sql->num_row>0){
$status=1;
}
else{
$status=0;
}
echo $status;
die;}
?>
HTML:
<right>
<form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required>
<input type="submit" id="submit">
<div id="msg" class="form-group"></div>
</form>
</right>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "") {
$("#msg").html("");
$("#submit").attr('disabled', true);
} else {
$.ajax({
url: "check_availability.php",
data: $(this).serialize(),
type: "POST",
success: function(data) {
if (data == 1) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#submit").attr('disabled', true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#submit").attr('disabled', false);
}
}
});
}
});
});
</script>
Related
I tested this script in Safari, and there it works, but I tried in Chrome, and there it does not work, and doesn't print the $status. What's the problem?
HTML file:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<span id="success"></span>
<form id="upload" method="post" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="imagefile" id="imagefile">
<input type="submit" name="uploadsubmit" id="uploadsubmit">
</form>
<script>
$(document).ready(function(){
$('#upload').on('submit', function(e) {
e.preventDefault();
var username = $('#username').val();
if (username == '') {
alert("Empty!");
} else {
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
$('#success').html(data);
alert("Success!");
}
});
}
});
});
</script>
PHP file:
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$con=mysqli_connect("localhost","root","","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status = '';
if(isset($_POST['uploadsubmit'])) {
$username = $_POST["username"];
if($_FILES['imagefile']['name'] != '') {
$target = "/images";
$target = $target . basename($_FILES['imagefile']['name']);
if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $target)) {
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (username,images)
VALUES ('".$username."','".$target."')");
mysqli_close($con);
$status = "Successfull upload with image!";
$imagefile = pathinfo($target, PATHINFO_EXTENSION);
$check = getimagesize($target);
if ($check !== false) {
echo "This file is image - " . $check["mime"] . ".<br>";
$uploadOk = 1;
} else {
echo "This file is not image!";
$uploadOk = 0;
}
} else {
$status = "Sorry, we have problem!";
}
} else {
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (username,images)
VALUES ('".$username."','no')");
mysqli_close($con);
$status = 'Successfull upload without image!';
}
echo "Status: {$status}";
}
?>
So after validating the form via Jquery, I like to know if the username and password are valid. If they are, it should redirect to another page, else I want to find a way of showing it to the user. At this point, I'm really confused. Here's the jquery code:
$(document).ready(function(e) {
$('.error').hide();
$('#staffLogin').submit(function(e) {
e.preventDefault();
$('.error').hide();
uName = $('#staff_username').val();
pWord = $('#staff_password').val();
if(uName == ''){
$('#u_error').fadeIn();
$('#staff_username').focus();
return false;
}
if(pWord == ''){
$('#p_error').fadeIn();
$('#staff_password').focus();
return false;
}
$.ajax({
type : 'POST', url : 'staff_access.php', data : 'uName='+uName+'&pWord='+pWord,
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
})
});
});
PHP:
<?php
include('admin/config.php');
$username = $_POST['uName'];
$password = $_POST['pWord'];
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
if ($conn) {
$qry = "SELECT lastname, firstname, FROM staff_user WHERE username='".$username."' AND pass='".$password."";
$res = mysqli_query($qry);
$num_row = mysqli_num_rows($res);
$row=mysql_fetch_assoc($res);
if ($num_row == 1) {
session_start();
$_SESSION['login'] = true;
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['username'] = $row['username'];
echo "true";
}
else{
echo "false";
}
}
else{
$conn_err = "Could not connect.".mysql_error();
}
mysqli_close($conn);
?>
FORM:
<form name="staff_login" method="post" action="" id="staffLogin">
<fieldset>
<legend>Staff Login</legend>
<span class="fa fa-user fa-5x"></span>
<br><br>
<input type="text" name="staff_username" id="staff_username" placeholder="Username">
<br><span class="error" id="u_error">Username Required</span><br>
<input type="password" name="staff_password" id="staff_password" placeholder="Password">
<br><span class="error" id="p_error">Password Required</span><br>
<span class="error" id="val_error">Incorrect Username and Password combination</span>
<input type="submit" name="staff_login" value="Login">
</fieldset>
</form>
Your ajax data is sent in wrong format. POST data should be sent as an object.
$.ajax({
type : 'POST',
url : 'staff_access.php',
data : {
uName: uName,
pWord: pWord
},
dataType: 'text',
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
});
Also avoid using texts like 'html'. You may end up getting unnecessary errors due to that.
Use more relevant words like "success: function(response)"
Try to define a dataTpe in your ajax config - dataType: "html"
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});
I want to check if the username is taken before the form is submitted.
As far as I can understand I have to use AJAX to get data from my database in javascript. How do I send the username to the PHP file?
This is my form:
<form id="loginForm" action="register.php" method="post">
<p>Register:</p>
<p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
<p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>
//Username
<p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
<span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
<span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>
<p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
<input type="submit" value="Register">
</form>
This is the validateUsername() function:
function validateUsername(username) {
var re = /[a-zA-Z0-9]/;
alert(username.length);
if(re.test(username) && username.length > 5) {
document.getElementById('username').style.backgroundColor = "green";
document.getElementById('usernameError').style.display= "none";
--error;
} else {
document.getElementById('username').style.backgroundColor = "red";
document.getElementById('usernameError').style.display= "block";
++error;
}
//here i want to check if the user name is taken
}
If the username is taken, I want to display the 'usernameTaken' span.
Otherwise, I want to hide it.
Here is the PHP file that checks if the username is already in the database:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = //The username;
$username = mysqli_real_escape_string($link,$username);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0) {
//if the username is NOT taken
return true;
} else {
//if the username IS taken
return false;
}
mysqli_close($link);
?>
How is this done?
JS - JQUERY AJAX
$.ajax({
url: 'register.php', data: {action: 'isUserNameTaken', params: [username]},
type: 'post',
success: function(data) {
//Do Something
}
});
PHP
<?php
function isUserNameTaken($username) {
//Do Something;
}
if(!empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'isUserNameTaken':
$username = '';
if(!empty($_POST['params'])) {
$username = $_POST['params'][0];
}
isUserNameTaken($username);
break;
}
}
?>
You could do it this way:
On client side:
function validateUsername(){
if(//test username input for length...) {
$.ajax({
type: 'POST',
url: 'validate.php',
data: { username: username },
success: function(response) {
if(response==0){
//username is valid
}
elseif(response==1){
//username is already taken
}
elseif(response==2){
//connection failed
}
}
});
}
else{
//display "username is too short" error
}
}
validate.php:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
echo json_encode(2);
}
else{
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
echo json_encode(2);
}
else{
$username = $_POST["username"];
$username = mysqli_real_escape_string($link,$username);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0) {
//if the username is NOT taken
echo json_encode(0);
}else {
//if the username IS taken
echo json_encode(1);
}
mysqli_close($link);
}
}
?>
You can also make this function validateUsername by calling it with onkeyup function in jquery so every time a user types something into the input field, the username will be checked....
I have an ajax request that looks like this
$(document).ready(function() {
$(document).on('click', '#submit', function() {
var UserName = $('#username').val();
var PassWord = $('#password').val();
console.log(UserName);
$.ajax({
type: 'POST',
url: 'ajax/Login.php',
dataType: "text",
data: {
username: UserName,
password: PassWord
},
success: function(data) {
alert(JSON.stringify(data));
window.location='pages/mainpage.php';
},
error: function(data) {
alert('Login Error');
//window.location='../index.php';
}
});
});
});
and my php is like this
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
echo "Welcome ".$username;
}else{
echo "Password incorrect";
}
}
}else{
echo "Username is empty";
}
When i dont put anything in username i am expecting that the alert will be Username is empty same as when password is empty alert should be Password incorrect but i am getting "\r\n\" but if put some in username like John it will alert Welcome John"\r\n\" why is this happening?how to make it alert Username is empty when username is empty same with password?any idea is accepted..
Try this: in ajax section, dataType: "text", change to dataType: "json", and server php code is following: it may work
//put this function top of this page
ob_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$json="";
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
$json.="Welcome ".$username;
}else{
$json.="Password incorrect";
}
}
}else{
$json.="Username is empty";
}
ob_end_clean();
echo json_encode($json);
?>
I change isset to !empty fixed the problem