check if username exists with bvalidator (jquery validation plugin) - php

I'm using bvalidator (jquery validation plugin) to check if a username exists in the database. They have an example on their documentation. However, I have no idea how it works. You can read more on that example here:
http://karmela.fsb.hr/~bmauser/bvalidator/documentation.html#serversidevalidation
I tried creating my own. However, It always tells me that the username is already taken no matter what... I'm a complete newbie when it comes to AJAX. I barely know it. So anyway, here's what I created so far...
index.php (the main page)
<script type="text/javascript">
$(document).ready(function () {
$('#register').bValidator(optionsRed);
});
function checkUsername(username) {
$.post("checkusername.php", { username: username }, function(data) {
if (data == 0) {
ret = true;
} else {
ret = false;
}
return ret;
});
}
</script>
<input type="text" name="username_register" id="textstyleid" data-bvalidator="checkUsername,required,rangelength[5:20]" data-bvalidator-msg="This username is not valid or already taken."/>
checkusername.php (checks if username exists)
<?php
require '../connect.inc.php';
if (isset($_POST['username'])) {
$username = mysql_real_escape_string($_POST['username']);
if (!empty($username)) {
$username_query = mysql_query("SELECT COUNT(uid) FROM users WHERE username='$username'");
$username_result = mysql_result($username_query, 0);
if ($username_result == 0) {
return 0;
} else if ($username_result == 1) {
return 1;
}
}
}
?>
Edit
I noticed a 404 error. I fixed that. The PHP and AJAX is working. It gives me a 0 or 1 depending on the text entered in the preview. However, the problem still exists. I think its because of this line of code. I don't really understand what it means. What is data?:
if (data == 0) {
ret = true;
} else {
ret = false;
}
return ret;

After looking at it further the problem is your php, you need to use mysql_num_rows around your result to compare with 0 recs returned, the result object itself will only give u a resource id if echo'ed out

Try this one
if (data == 0) {
echo json_encode(TRUE);
} else {
echo json_encode(FALSE);
}

Related

Problem creating a login authentication using ajax

I'm trying to create an AJAX script that calls a PHP script to check the entered username and password. The PHP script simply returns "true" if the entered details are correct and false if otherwise.
At the end of the AJAX script, I've placed a simple if else condition for true/false returns. Every time the PHP script returns true, the AJAX scripts jumps to else part overlooking the if.
I know there might be some stupid mistake or it is probably a ludicrous question but I'm stuck on it since many days. Stack is the last resort!
Here's my AJAX SCRIPT
function authenticate()
{
//XMLHttpRequest Object
var xhttp = new XMLHttpRequest();
var email = document.getElementById('email').value;
var pass = document.getElementById('pass').value;
var url = "php/user_authentication.php";
var url2 = "php/user_authentication.php?email=" + email + "&pass=" + pass;
var result = "";
xhttp.open("GET", url2, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
xhttp.onreadystatechange = function f()
//f() would be called everytime the onreadystatechange property changes the value
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
alert(this.responseText);
result = this.responseText;
if (result == "true")
//!! -> NOT ENTERING THIS PART EVEN WHEN result="true" !!
{
alert("Inside true");
document.getElementById('email_pass').innerHTML = 'login successful';
} else {
document.getElementById('email_pass').innerHTML = 'login failed';
alert("2 " + xhttp.responseText);
}
}
}
}
Here's the PHP script [user_authentication.php]
<?php
//User Authentication
//1.Including the database_connection.php
include "database_connection.php";
//2.1.Fetching the user id and password from the form
$email = $_GET['email'];
$pass = $_GET['pass'];
//2.2.Defining th select query
$qry = 'select * from user_auth where Email="'.$email.'" and Password = "'.$pass.'"';
//3.Executing the query and storing it to result
$result = mysqli_query($connection,$qry);
//authenticating
if(mysqli_num_rows($result)>0)
{
echo "true";
}
else
{
echo "false";
}
?>
Obligatory comment about prepared statements in php and sql PHP Manual.
But I would try to cast the comparison
if (result == "true")
to boolean like so
if (Boolean(result) === true)
I admit, my knowledge of ajax and JS is limited but in such cases Ive learned to not trust JS automatic type casting. Note also that I would definately use 3x= if we are casting result to a boolean.
The issue was,
I was getting some extra spaces along with my responseText that made the following condition false every time I got "true" in my responseText.
if (result == "true")
//Turns false because result.length = 11 (extra empty spaces due to some unknown reasons)
The solution was as follows :
Changing the return value in my PHP to 't' and 'f'
Using the slice method to slice the first variable of responseText to eliminate all the white-spaces in the string and then making further comparison
xhttp.onreadystatechange = function f()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
result = this.responseText;
var temp = result.slice(0,1);
//This will only select the first char in the result string
if (temp == "t")
document.getElementById('email_pass').innerHTML = 'login successful';
else
document.getElementById('email_pass').innerHTML = 'login failed';
}
}
$result not getting "true" make sure or double check below:
Html element IDs are (email, pass)
Database connection work properly,
$qry: select query related fields have matched with table columns
$result will get true only if requested email and password exits in database user_auth table
I think it may help...good luck

jQuery AJAX method returns current page

First, let me say that I've looked through other similar questions on this site and the jQuery documentation. So far I haven't found something that fixes my issue.
I'm trying to setup a login form for logging in using an email address and password. I have a PHP-only solution that works just fine, but I'm trying to add AJAX functionality as well.
The code I'm using now returns the whole page that's making the AJAX call. Just for some extra info, I'm using jQuery 1.10.2 and PHP 5.4.12. This is also my first time setting up a site to use a PHP script for deciding what other scripts to use based on what data is sent to it, so please bear with me.
Here's my form:
<form id="employee_login" name="employee_login" action="portal.php" method="post">
<input type="text" name="email" placeholder="Email address">
<input type="password" name="password" placeholder="Password">
<button id="login" type="submit" name="submit">Submit</button>
</form>
<div id="error_box">
<?php if(isset($GLOBALS['loginError']) && $GLOBALS['loginError'] != '') { ?>
<p class="error"><?php echo $GLOBALS['loginError']; ?></p>
<?php } ?>
</div>
Here's my AJAX function:
function ajaxValidate(email, pass, error) {
if($(email).val() == '' || $(pass).val() == '') {
$(error).html('<p class="error">You must enter your email address and password!</p>');
}
else {
$.ajax({
type: 'POST',
url: '/php-modules/ajax_filter.php',
dataType: 'text',
data: { emailAddr: $(email).val(), password: $(pass).val()},
success: function(text, textStatus, jqXHR)
{
console.log(Date() + ': ' + text);
try{
if( IsType(text, 'json') ) {
var ajaxData = $.parseJSON(text);
if(ajaxData['error'] != null && ajaxData['error'] != 'undefined')
$(error).html('<p class="error">' + ajaxData['error'] + '</p>');
else if(ajaxData['is_email'] != 1)
$(error).html('<p class="error">You must enter a <strong>VALID</strong> email address.</p>');
else if(ajaxData['is_email'] == 1)
document.location = jqXHR.getResponseHeader('Location');
else
$(error).html('<p class="error">You must enter your email address and password!</p>');
}
else if( IsType(text, 'html') ) $(error).html( $.parseHTML(text) );
else if( IsType(text, 'xml') ) alert('Data is XML.');
}
catch(e) {
$(error).html('<p class="error">' + e.description + '</p>');
console.debug(e);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$(error).html('<p class="error">' + jqXHR.status + ' ' + errorThrown + ' ' + jqXHR.responseText + '</p>');
}
});
}
}
The script I'm sending the AJAX call to is only setup for 1 request so far. I intend to add more later. I'm not sure if I've setup too many checks either, but I wanted to be safe since I'm not very familiar with something like this. And the "unidentified error" thing I added just today was a replacement for a "return false" that I thought could've been causing the problem. Here's the code:
<?php
// a filter for all AJAX requests
// for email checking
if( isset($_POST['emailAddr']) ) {
require_once('login.php');
if(isset($GLOBALS['loginError']) && $GLOBALS['loginError'] != '') {
echo '{"error":"' . $GLOBALS['loginError'] . '"}';
} else echo '{"error":"Unidentified error"}';
}
// if $_POST isn't set, isn't an array, or has a length less than 1, return an error
else if(!isset($_POST) || !is_array($_POST) || count($_POST) < 1) {
echo '{"error":"No data sent"}';
}
// if the previous check fails, invalid or insuficient data was sent
else {
echo '{"error":"Could not process request"}';
}
?>
The last piece is my login checking script. I've omitted the actual query and table fields because those parts work fine when using my PHP-only solution.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// halt execution if the login fields are empty
if((!isset($_POST['emailAddr']) || $_POST['emailAddr'] == "") && (!isset($_POST['password']) || $_POST['password'] == "")) {
$GLOBALS['loginError'] = 'You must enter your email and password!';
}
else {// check for valid email
require_once('is_email.php');
if( !is_email($_POST['emailAddr']) ) $GLOBALS['loginError'] = 'You must enter a valid email address!';
else if($_POST['emailAddr'] != "" && $_POST['password'] != "") {
try{
// PDO setup
include('pdo.php');
$con = createPDO();
// PDO statement preparation and execution
$query = $con->prepare("[query code];");
$email = $_POST['emailAddr'];
$password = $_POST['password'];
// returned PDO query data
if($query->execute( array($email) ) ) {
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
if(strtolower($email) == strtolower($row['email']) && $password == $row['password']) {
// set session data
$_SESSION['user_id'] = $row['[id field]'];
$_SESSION['name'] = ucfirst($row['[name field]']);
$_SESSION['email'] = $row['[email field]'];
session_regenerate_id();
header("location: /");
}
else $GLOBALS['loginError'] = 'ID or password incorrect!';
}
}
} catch(Exception $e) {
$GLOBALS['loginError'] = $e->getMessage();
}
}
else $GLOBALS['loginError'] = 'You must enter your email and password!';
}
}
?>
I've cut out an unnecessary function and return false; lines, added the console.log(); method, changed the email: value name in the ajax data: option to emailAddr: (in my PHP code too) in case of a name conflict between it and my email variable, and changed my code to parse for HTML in case of PHP generating HTML error messages. My parentheses, braces, and brackets seem to be matched ok (I checked using Sublime Text's parenthesis/brace/bracket highlighting to check), the form checking portion of the script works fine.
I'm honestly at a loss...
Also, thanks to everyone who reads through this long-winded post.
Question updates:
I just realized that parsing code in the try is working correctly. Since the $.parseJSON doesn't work, it's skipping down to the if statement for parsing HTML and that one is working.
Code changes:
I replaced some return statements with echo, per Morganster.
When you are going to return data across an ajax call, you must print your data.
For example,
$var['error']="Could not process request";
echo json_encode($var);
The problem is fixed. Someone named Scott Sawyer said header("Location: /") would cause the $.ajax() method to return the whole current page. The redirect seems to be working now. Thanks for the input everyone.

Couldn't get response from database with jQuery using PHP post request

I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>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;
}
?>
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>
You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});

echo out php variable in jQuery

this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.

sending php array to javascript function onclick

Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)

Categories