Checking for existing users in DB using Ajax and PHP - php

I'm running into a problem where the code keeps on showing that the user name is available, even though it is existing in the DB. Can anyone solve the problem that I'm running into? Down below is my code.
PHP
// Define $username
$username=$_POST["emailAddress"];
// Create Connection
$db = new mysqli($server, $user, $password, $database);
// Check Connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
// SQL query to fetch registerd users and finds user match.
$query = "SELECT email_address FROM users WHERE email_address='$username'";
$result = mysqli_query($db,$query);
$rows = mysqli_num_rows($result);
//if number of rows fields is bigger them 0 that means it's NOT available '
if($rows>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
mysqli_close($db); // Closing Connection
jQuery
$(document).ready(function () {
//when button is clicked
$('[name="checkAvail"]').on("click", function () {
check_availability();
});
});
//function to check username availability
function check_availability() {
//get the username
var username = $('[name="emailAddress"]').val();
//use ajax to run the check
$.post("checkusers.php",
function (result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
}
HTML
<div class="form-group">
<button class="btn btn-default" name="checkAvail">Check Availability</button>
<label for="emailAddress" class="col-sm-5 control-label">Email:</label>
<div class="col-sm-4">
<input type="email" class="form-control" id="emailAddress" name="emailAddress" placeholder="Email" autocomplete="off">
</div>
</div>

Your ajax doesn't send any data...so $_POST["emailAddress"]; is going to be empty in your php
You need to add a data object as second argument of $.post
$.post("checkusers.php",{emailAddress : username },function (result) {
// success handing code left out for clarity
});
Also you should check that the input isn't empty before user is allowed to check it. No point in sending invalid empty values to server.
There are lots of simple javascript validation plugins you can use.
Similarly on server should be valididating the user input. This is the most important point of validation because javascript can be worked around to allow sending anything

You aren't sending any data to the Post Page.
$.post( "checkusers.php", { emailAddress: username})
.done(function( data ) {
if (data == "1") {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}
});
Check the jQueryDocumentation

according to your php script try this if (result==0)
function (result) {
//if the result is 0
if (result == 0) {
//show that the username is available
$('.existingUser').html(username + ' is Available');
} else {
//show that the username is NOT available
$('.existingUser').html(username + ' is NOT Available');
}

Related

Not redirecting to another page after successful ajax request complete

I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.

PHP and MySQLi query always returning 0

The following code seems to be not working correctly. I'm new to PHP and jQuery.
php:
<?php
//if (!defined('BOOTSTRAP')) { die('Access denied'); }
//if we got something through $_POST
if (isset($_POST['postcode_locator_search'])) {
// here you would normally include some database connection
//include('config.local.php');
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','test','c#W)ukmd[0bm','test');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
// never trust what user wrote! We must ALWAYS sanitize user input
$postcode_q = mysqli_real_escape_string($mysqli, $_POST['postcode_locator_search']);
$postcode_q = htmlentities($postcode_q);
// A select query. $result will be a `mysqli_result` object if successful
$result = mysqli_query("SELECT description FROM cscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
// Fetch all the rows in an array
echo '0';
}
$mysqli->close();
}
?>
JS / HTML:
{assign var="prod_id" value=$product.product_id}
<form action="search_postcode.php" method="post" class="postcode_locator_form" name="postcode_locator_form">
<div class="ty-control-group">
<label for="postcode_locator_search{$block.block_id}" class="ty-control-group__title">{__("postcode_search")}</label>
<p class="filling-notice">{__("postcode_search_desc")}</p>
<div class="ty-input-append ty-m-none">
<input type="text" size="20" class="ty-input-text" id="postcode_locator_search" name="postcode_locator_search" value="{$postcode_locator_search.q}" />
{include file="buttons/go.tpl" but_name="postcode_locator.search" alt=__("search")}
</div>
</div>
</form>
<div class="filling-status filling-success">
<h3>Add filling to your bean bag</h3>
<p>Searched postcode: <span class="searched-postcode"></span></p>
<p class="beans-msg">{__("add_some_beans_success")} {__("click_here")}</p>
</div>
<div class="filling-status filling-failure">
<h3>Add filling to your bean bag</h3>
<p>Searched postcode: <span class="searched-postcode"></span></p>
<p class="beans-msg">{__("add_some_beans_error")}</p>
</div>
<script>
$(function() {
$(".filling-status").hide();
$(".postcode_locator_form .ty-btn-go").click(function() {
// getting the value that user typed
var searchString = $("#postcode_locator_search").val();
// forming the queryString
var data = 'postcode_locator_search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "search_postcode.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$(".searched-postcode").html(searchString);
},
success: function(data){ // this happens after we get results
console.log(data);
if(data == '0'){
$(".filling-status.filling-success").show();
} else if(data == '1'){
$(".filling-status.filling-failure").show();
}
}
});
}
return false;
});
});
</script>
The communication is all working, but it always returns 0 as a success from whatever I search for and seems to not check database for the result.
What I need is if I search something and it's a match, to return 0 as a success but if not found / a match to return 1 as a failure.
If you want to retrieve your data:
$result = mysqli_query("SELECT description FROMcscart_postcode_location_descriptions WHERE cscart_postcode_location_descriptions LIKE '%" . $postcode_q . "%' ORDER BY cscart_postcode_location_descriptions LIMIT 1");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
echo '1';
} else {
// Fetch all the rows in an array
while($row = mysqli_fetch_assoc($result)){
echo $row['id']; //prints the resulted id
}
}
Use mysqli_num_rows to detect if you have a result
if($result === false or mysqli_num_rows($result) === 0) {
echo '1';
}
I would recommend breaking this into two if conditions though so that you handle errors separately from a query with no result

Validate promo code from MySql table and mark as "used" when form is submitted

I have an HTML form starting with an input field, where the user have the option to write a promo code to get some discount ....
What I am trying to do here. I need to create a keyup functionto check if the typed code is found in the MySql Promo Codes table.
If found, write something in the placeholder ...., else, write something else ....
Also if the form is submitted in need the PHP to write 'Yes' in the code corresponding MySql Used column...
<form id="form" class="form" name="RevitForm" action="form_revit_architecture_submitted" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
<div class="field" style="background-color:#f3f3f3;">
<span id="promo-msg" style="color:#093; position:relative; bottom:3px; font-style:italic; font-size:13px">[HTML is replaced when successful.]</span>
<center><input style="font-family:Lato; text-align:center; max-width:200px;" type="text" id="PromoCode" name="PromoCode" maxlength="5" size="15px" placeholder="Promo Code"></center>
</div>
//other input fields
</form>
<!-- Promotion Code Match -->
<script>
$("#PromoCode").keyup(function() {
if ($(this).val().length == 5) {
//post the code and check the it in the MySql table thru the PHP file "request.php"
//if code found {write something in $(#promo-msg) } else {do something else}
}
});
</script>
And in the PHP in need to excute something like
<?PHP
$code = ucwords($_POST['PromoCode']);
$con=mysqli_connect("localhost","x","y","academy_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
// if $code is found and the corresponding `Used` column does not == 'Yes' return as found
//else return as not found
?>
To do that, we need 2 files.
HTML, form + jQuery AJAX keyup event and check DB
PHP connect to DB to check the promo code
1.HTML
<html>
<head>
<title>Promo check</title>
<!-- load jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 10;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' is already used correct.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<input type='text' id='code'>
<div id='Promo_code_status'></div>
</body>
</html>
2.PHP: check_code.php
You will need to use your connection data ($host, $user, $pass, $dbdb) and maybe change the table & field names.
<?php
//connect to database
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select promoCode, used from testtable where promoCode = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
Do it like this:
"SELECT * FROM Promo Codes WHERE Code LIKE '$code' AND Used='yes' "
Also,To update parameter 'used':
UPDATE Promo Codes SET used='Yes' WHERE Code= '$code'
For the keyup function, you need to learn about AJAX requests. Since it's the medium for communicating with the server through the client
jQuery AJAX: http://api.jquery.com/jquery.ajax/

Ajax and PHP with database connection

i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.

using jquery to process a php script based on returned values

Code Logic:
1) User types in username and password, user clicks submit.
2) jQuery script pulls the php script below.
3) jQuery determines which php value is returned.
4) if value 1 is returned, jquery and php will process what's in the if statement.
5) if value 0 is returned, jquery and php will process whats in the else statement.
How do I successfully make the code below work alongside the logic above? I can't seem to make a connection in my mind.
class1.php
$email = mysql_real_escape_string(strip_tags($_POST["username"]));
$password = sha1($_POST["password"]);
$sql = "SELECT * FROM users WHERE username = '{$email}' AND password = '{$password}'";
$result = mysql_query($sql) or exit("ERROR: " . mysql_error() . "<br>IN QUERY: " . $sql);
if (mysql_num_rows($result) > 0) {
return 1;
$row = mysql_fetch_array($result);
$_SESSION["userid"] = $row['user_pid'];
} else {
return 0;
$userid_generator = uniqid(rand(), false);
mysql_query("INSERT INTO users (user_pid, email, password, datetime_registered, is_leader) VALUES ('$userid_generator', '{$email}', '{$password}', NOW(), 'no')");
$id = mysql_insert_id();
$leaders = mysql_query("SELECT * FROM users WHERE is_leader LIKE '%yes%'");
while($rows = mysql_fetch_array($leaders)) {
if ($rows['is_leader'] == 'yes') {
$leader_id = $rows['user_pid'];
mysql_query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type)
VALUES('$leader_id', '$userid_generator', NOW(), 'full')");
echo "new user created and logged in";
}
$_SESSION["userid"] = $userid_generator;
}
}
?>
index.html:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.loading {
float:right;
background:url(img/ajax-loader.gif) no-repeat 1px;
height:28px;
width:28px;
display:none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var username = $('input[username=username]');
var password = $('input[password=password]');
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "processing/class1.php",
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
alert('success');
//if process.php returned 0/false (send mail failed)
} else { alert('failure');
}
});
return false;
});
});
</script>
<input type="text" id="username" name="username" />
<input type="password" id="password" name="password" />
<input type="submit" id="submit" />
<div class="loading"></div>
<div id="display"></div>
Ajax is effectively a "blind client". So, think of what you would see if you were to manually view the php script, and interpret that as what your ajax callback would be parsing.
Having said that, the "0/1" return you're looking for is dependent on one (of many) echos going on in your script (most notably the following):
echo "new user created and logged in";
if you want the ajax callback to recognize a 0/1, this would need to only echo a "1" (not verbiage), where as errors would simply return a "0" (such as your or exit("ERROR...).
EDIT
Also, looking further, your var data = 'name=' component (assuming you want it to align with the PHP $_POST["username"]) should probably be renamed to var data ='username=' (the data property of the ajax call is what' populating your PHP's $_POST variables, so names need to align).

Categories