Check username JQuery Ajax - php

I have the following ajax call
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
I want the page to stay if the username is taken, else redirect to whats in the action attribute of the for.
Obviously this isn't working. But why? I would like to not use preventdefault, so that I could get a better understanding of where the problem and solution is.
EDIT:
The server code
<?php
$seed = 'n48sma94r98';
$email = $_POST['un'];
$mysqli = new mysqli('localhost','uml','uml','uml');
if (!$mysqli)
{
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
$query = "Select User_Email as Email from user2 where User_Email = AES_ENCRYPT('$email','$seed') ";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
echo "1";
}
else
{
echo "2";
}
?>
The entire form minus the meta:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="Resources/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">$(document).ready(function(){
$("#login").submit(function() {
var un = $('#username').val();
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
});
});
</script>
</head>
<body>
<form name="login" id="login" method="post" action="dsds.html">
UserName<input type="text" name="username" id="username"value="">
Password<input type="text" name="password" id="password" value="">
Password Again<input type="text" name="passwordagain" id="passwordagain" value="">
<input type="hidden" name="NewClass" id="NewClass" value="true">
<input type="submit" name="submit" id="submit" value="submit">
</form>
<span id = "mike"></span>
</body>
</html>

Some advice. Name your variables and methods. What is 'un' and 'data'? What do they contain?
Also what type of data is returned? String, HTML, XML, JSON?
If you want to redirect you can use window.location = 'someURL';
To send a form you can do this: $('#form-id').submit();
You could return more meaningful messages, like usernameExists,usernameFound or usernameNotExists,usernameNotFound. Even if you are the only one working on this project, when you go around and ask for help, peeps need to understand your code. It should read like sentences.

I suppose you use
if(data!=1)
to see of the username was taken or not?
Did you try to see the value of data using some sort of a debugger? (or even an alert()).
As I suppose you are not sending a 1 from the server when the username is already taken...

I usually use OK as response indicator (or whatever you call that). If the response (your data) starts with OK it's positive, otherwise the entire message is the error:
In Javascript:
success: function(response) {
if ( 'OK' == response.substr(0, 2) ) {
// Okay, so show something green or do nothing
var message = response.substr(2); // Everything after "OK"
}
else {
// Not okay, so show something red or redirect
var goto = response;
// The entire response message `response` is the target destination
// If you don't want PHP to define the redirect location, just hard code it right here
window.location = goto;
}
}
And in PHP:
$result = $mysqli->query($query);
$usernameExists = $result->num_rows > 0; // A nice boolean
exit( $usernameExists ? '/error.html' : 'OKThis username is fine' );
PS. The return false in the success function does nothing. You can omit that.
edit
Without changing the PHP:
success: function(response) {
if ( '1' !== response ) {
window.location = 'error.html';
}
}
Since response is a string, I'd check for that (and not a number). And it never hurts to check for identicallity (===) instead of equality (==).

Related

PHP alert comes on loading page and causes page to go blank

I created a login page connected to a database. However, in order to give a message, I used alert. Now, upon loading the page i immediately get an 'Invalid Username' alert. I want the alert to appear only after the Login Button is pressed.
Also, upon pressing the Login Button, the page goes blank and then the alert appears and then on clicking OK, the html page loads. How do I get the alert on the same page.
The file: login.php
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form id="Form" method="post">
<input id="Username" name="Username" type="text" placeholder="Username"><br>
<input id="Password" name="Password" type="password" placeholder="Password""><br>
<button id="Button" name="Login" type="submit">Login</button><br>
</form>
</body>
</html>
<?php
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
echo "<script>alert('Login Successful');</script>";
}
else
{
$check=mysqli_query($conn,"select Username from members where Username='$uname'");
if(mysqli_num_rows($check)==1)
{
echo "<script>alert('Invalid Password');</script>";
}
else
{
echo "<script>alert('Invalid Username');</script>";
}
}
?>
It might be harsh for such a seemingly small thing, but the solution here is to use AJAX. Assuming you dont know AJAX, I'd recommend you to learn it, after using this solution.
You also need jQuery for this.
First off, you need to include put the PHP part in another file, lets say: login.php:
<?php
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_POST['Username'];
$passw=$_POST['Password'];
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
echo json_encode(array("msg"=>"Login Successful"));
}
else
{
$check=mysqli_query($conn,"select Username from members where Username='$uname'");
if(mysqli_num_rows($check)==1)
{
echo json_encode(array("msg"=>"Invalid Password"));
}
else
{
echo json_encode(array("msg"=>"Invalid Username"));
}
}
?>
Next you'll make a JS file:
$('#form').submit(function(event) {
$.ajax({
method: "POST",
url: "login.php",
data: $("#form").serialize()
})
.done(function( data ) {
alert(data['msg']);
});
}
Sorry if I missed a part but there's a lot to do and learn for you to understand this at all.
Because the PHP is server side code, you are loading the value mysqli_num_rows($check)==1, before your page has been presented to the user, so therefore, no credentials have been entered. If you want to perform an action on the button click, you need to use client side code, such as javascript. Here is a simple solution I have created for you.
This is your "index.php" page where the login form is:
<html>
<head>
<title>Please login</title>
</head>
<body>
<input id="Username" name="Username" type="text" placeholder="Username"><br>
<input id="Password" name="Password" type="password" placeholder="Password""><br>
<button id="Button" name="Login" onclick="checkCredentials();">Login</button><br>
<script type="text/javascript">
function checkCredentials(){
var username = document.getElementById('Username').value; //Get the text from username field
var password = document.getElementById('Password').value; //Get the text from password field
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Make your alert
var response = JSON.parse(this.responseText);
if(response.status == 200){
alert(response.alert);
/**
* Here, put whatever else you want to do when login is successful!
* My best guess is that you'd redirect the user to a page where a new
* PHP session is started. If you need help with this, please ask :)
**/
} else {
//Login has failed, display the response message
alert(response.alert);
}
}
};
//We're sending the password in plaintext over a GET request. I've done this for simplicity.
//You should NOT send the password in plaintext on the production system. Doing this is insecure. Hash it before you send it.
request.open("GET", "login.php?username="+ username +"password=" + password, true);
request.send();
}
</script>
</body>
</html>
Now that you have your login page created, you can make the login.php page, which is a backend script for checking login details.
<?php
$loginStatus = array("status" => 403, "alert" => "forbidden");
$conn=mysqli_connect ('localhost','root','','test');
$uname=$_GET['username'];
$passw=$_GET['password'];
//Don't use this line in production, you should use a prepared statement instead
$check=mysqli_query($conn,"select Username from members where Username='$uname' and Password='$passw'");
if(mysqli_num_rows($check)==1)
{
$loginStatus = array("status" => 200, "alert" => "Login Successful!");
}
else
{
$check=mysqli_query($conn,"select Username from members where username='$uname'");
if(mysqli_num_rows($check)==1)
{
$loginStatus = array("status" => 403, "alert" => "Invalid Password!");
}
else
{
$loginStatus = array("status" => 403, "alert" => "Invalid Username!");
}
}
echo json_encode($loginStatus);
?>
The code explained:
On your "index.php" there is a peice of javascript which makes a request (in the background) to your auth page (login.php). Login.php returns a JSON array containing information on the login, if it was successful or not, as well as a message which gets displayed in a javascript alert();
What's a prepared statement?
A prepared statement is a database query that works with parameters rather than the values directly. This is much more secure and will help prevent SQL injection to your database. See this question for more info how to do it (stack overflow link)
You only want that PHP to run if the form is submitted. So wrap all your PHP code in an if condition.
if (!empty($_POST)) { .... rest of php code here ... }

PHP array with Ajax and Jquery - How to create dropdown from the data?

This is the first time i've used AJAX and PHP. I've written a simple login page (below). As you can see, Ajax will send the username to getLocations.php on blur, which i coded with the help of this site and youtube (i'm leaving out the db connect bit, but it's there):
<!doctype html>
<html>
<head><title>Fetch JSON array Data</title>
<script src="http://10.28.1.90/DC_CRM_HOME2_USER_RIGHTS/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#username").blur(function() {
var sendu = $("#username").val();
$.ajax({
type: "POST",
url: "getLocations.php",
data: "username="+sendu,
success: function(response){
$("#result").html(locations+string+jqXHR);
//populate select with response...but how?
var locations = response.name;
for (var i in locations)
{
var vertical = locations[0];
$('select').append("<option value=\""+vertical+"\">"+vertical+"</option>");
}
}
});
});
});
</script>
</head>
<body>
<form method="post" action="#" onsubmit="return false;">
<input type="username" id="username" name="username" placeholder="username" value="" /><br><p>
<input type="password" id="password" name="password" /><br><p>
<select name="foo" id="foo">
<option></option>
</select><br><p>
<input type="submit" id="button" value="Login" />
</form>
</body>
</html>
getLocations.php:
$name = $_REQUEST['username']; //from ajax request
$query = "select LOCATION ";
$query .= "FROM dc_MASTER.DC_CNSLR_ACCESS dca ";
$query .= "JOIN dc.MEMBERS m ON dca.id = m.id ";
$query .= "AND m.EMAIL = '$name' ";
$Sresult = mysqli_query($mysqli, $query);
if( ! $Sresult) {
die("Database query failed: $Sresult");
}
$result = array();
while( $row = mysqli_fetch_array($Sresult) )
$list = array_push($result, array('name' => $row[0]));
$c = json_encode(array("result" => $result));
echo $c;
?>
At this point, my array is "loaded" and i'm able to see the response in firebug:
{"result":[{"name":"Chenal"},{"name":"Heights"}]}
However, i can't seem to get my select options populated. I feel like i'm making this harder than it should be (and i've been staring at it for quite a while). Thanks for the help guys.
You have to loop through the JSON returned by the PHP:
Demo: http://jsfiddle.net/L7a68y26/
var response = {"result":[{"name":"Chenal"},{"name":"Heights"}]}
var r = response.result;
for (var i in r)
{
$('select').append("<option value=\""+r[i].name+"\">"+r[i].name+"</option>");
}
In context:
$.ajax({
type: "POST",
url: "getLocations.php",
data: "username="+sendu,
// Added this so jQuery knows what kind of data is being returned
dataType: 'json',
success: function(response){
var r = response.result;
for (var i in r)
{
$('select').append("<option value=\""+r[i].name+"\">"+r[i].name+"</option>");
}
}
});
1) You haven't told jquery that you're expecting a json response back, so it'll just treat it as plain text.
$.post(
dataType: 'json' // <<--you need this
With that, jquery will automatically parse/decode the JSON into a native JS data structure
2) Then it's a simple matter of looping:
success: function(data) {
$.each(data, function(i, opt) {
$('select').blahblah + opt.name + blahblah
})
On the efficiency side of things, while it's sometimes a good idea to pass around data AS data, but if all you're going to be doing with the data is stuffing it into a form field, you might be better off just building the HTML on the server and passing that around directly.

Change Password PHP/Ajax/JQuery

I'm trying to create a form for changing a users password. No errors are being generated in the console but nothing is being updated. The validation side is also working so it must be down to the Ajax part?
Disclaimer: I know I shouldn't be using mysql in PHP, but I'm trying to get the basics down and will learn mysqli at a later date :)
Also, config.php is used in multiple other functions so I know config.php is fine.
Any idea what is going wrong?
HTML:
<fieldset>
<form method="post" name="password-form" id="form-password">
<label>Password:</label> <br>
<input type="password" name="password" id="password" value="" size="32" />
<br>
<br>
<label>Re-Enter Password:</label> <br>
<input type="password" name="password-check" id="password-check" value="" size="32" />
<br>
<br>
<input type="submit" value="Submit" id="passsubmit">
</form>
</fieldset>
JQuery:
$(function(){
$("#passsubmit").click(function(){
$(".error").hide();
var hasError = false;
var newpass = $("#password").val();
var checkVal = $("#password-check").val();
if (newpass == '') {
$("#password").after('<span class="error">Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#password-check").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (newpass != checkVal ) {
$("#password-check").after('<span class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) {return false;}
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {newpass:newpass},
success: function(){}
});
};
});
});
PHP:
<?php
session_start();
include('config.php');
$user_check=$_SESSION['login_user'];
$newpass=$_POST['newpass'];
$sql_rec = "select UserID from useradmin where username='$user_check' ";
$rs_rec = mysql_query($sql_rec);
$data_rec = mysql_fetch_object($rs_rec);
$userID = $data_rec->UserID;
$updatesql="UPDATE useradmin SET passcode='$newpass' WHERE UserID=$userID";
mysql_query($updatesql, $bd) or die(mysql_error());
?>
$bd is my MySQL connection details from config.php.
UPDATE:
I've added <div id="passsubmit2">123</div> to my page and changed the jquery to:
$(function(){
$("#passsubmit2").click(function(){
And it works perfectly, so it's only when using the form button that it doesn't work?
Figured it out eventually.
I needed to add event.preventDefault(); to prevent the normal form submit from firing.
Since you are sending form data to your server through an Ajax request, you dont need that input of submit type at first place, because this will try to submit the form on click and you will have to write additional code for stopping the default functionality of that submit button. So replace that submit button with simple html button or a link.
change your data inside ajax to
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {
newpass : newpass,
},
success: function(){}
});
};
because you are not sent the data to server and info variable not declared
Make sure to pass all the required data to the PHP server. Right now, from what I can see, you are passing an empty variable.
info={
newpass : newpass,
checkVal: checkVal
};
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: info,
success: function(response){
console.log(response);
}
});
On the PHP side:
<?php
$newPassword=$_POST['newpass '];
EDIT: Going a bit further with this, you really want to store a user ID (unique numeric ID) in the session rather then the username. Referencing through-out your mysql DB using the username as a unique value is a very poor idea (trust me, I made the same mistake).
Also, you should require users to enter their old password whenever changing a current password (what if they left the website up on their computer).

check availability of the username using ajax and jquery in codeigniter

Here I am trying to check that username input is available for the user or not. I am doing it in codeigniter.
Here is my view page:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<style type="text/css">
.no{color:red;}
.yes{color:green;}
</style>
<script>
$(document).ready(function(){
// unique user name checking ------------- starts here----------------
$("#username").blur(function(){
var form_data= {
action : 'check_username',
username : $(this).val
};
$.ajax({
type: "POST",
url : "check_unique_username",
data : form_data,
success : function(result) {
$("#message").html(result.message);
alert(result);
}
});
});
// unique username checking -------------- ends here-----------------
});
</script>
</head>
<body>
<form class="RegistrationForm" id="RegistrationForm" method="POST" action="">
<label for="username">User Name</label>
<div>
<input id="username" name="username" size="25" class="required" />
</div>
<input type="button" id="button1" name="button1" value="check availability" />
<div id="message"></div>
</form>
</body>
here is my controller code :
<?php
class Registration extends MX_controller {
function index(){
$this->load->view('registrationPage'); // this will load the registration page.
}
function unique_username() {
$action = $_POST['action'];
if($action=='check_username'){
$u = $this->input->post('username');
$users=array("jhon","neo","margo","hacker","user123");
if(in_array($u,$user)) {
echo json_encode(array('message' => "It is not available!"));
}
else {
echo json_encode(array('message' => "It is available!"));
}
}
}
}
?>
But my code is not working, where I am getting wrong,please help me out..showing only it is available for every username
Edited : I have changed my controller code...
You have not used # while using the id of the div, so use:
$("#message").html(result);
instead of $("message").html(result);
EDIT: An updated answer to an updated question.
It's actually pretty stupid none of us could see it, but the problem is this string: username : $(this).val. The reason is that .val is not jQuery's method that get's the value of a text field, it should be username : $(this).val() (with brackets).
This covers the first JS part, the next problem is a typo, you have url : "check_unique_username",, but it should be url : "registration/unique_username", (didn't have controller name, and had unnecessary check_ prefix while in controller the method was without it).
Next typo is in PHP - if(in_array($u,$user)) {, but we have an array $users, so change this to if(in_array($u,$users)) {, so PHP would not throw a notice.
Next problem is the missing line dataType: 'json', in AJAX request. We must put it so that JS could know what data type we are receiving and parse it in a correct way.
After that it should work. But I have some suggestion for you. Change the PHP, so that it would return not strings, but a boolean value. For example - true, if it's available, false if it's not.
if(in_array($u,$users)) {
echo json_encode(array('message' => false));
} else {
echo json_encode(array('message' => true));
}
That way it would be easier to manipulate this data in your JS code. For example you could add this code to the success part of your AJAX request:
success : function(result) {
if(result.message) {
$("#message").html("It's available!");
$("#button1").removeAttr('disabled');
} else {
$("#message").html("It's not available!");
$("#button1").attr('disabled','disabled');
}
}
And you will have your submit button enabled/disabled. This will make sure a normal user would not be able to submit the form if he entered a username that is taken.
Also I would change the event blur to keyup, that way you will have faster updates, but it's a bit more heavy on the server. Problem with blur event is that your user could fill the username and click on the button anyway, because blur event fires only after the user leaves the element.
Hope this helps!

How to pass variables to another php file afte succes jquery.ajax()?

I've a index.php for login users, and when press submit the following process occurs ...
1.- The user enters a number and password
2.- jQuery.ajax method is used () to connect to the file doLogin.php to process the data and if correct, print "echo 'success'" and make these variables sessiĆ³n: nControl , name, lastname, and typeUser
3.- Then in the method jQuery.ajax () takes "success" and makes a call to dashboard.php thus: "document.location.href = 'dashboard.php'"
Basic structure: Index.php (for login) --> functions.js (process inputs of index.php with jQuer.ajax()) --> dashboard.php(i want receive data from index.php to displa details user)
So the question that arises is:
That method would be best for you, after success in jQuery.ajax method () that sends data to the file dashboard.php? Because such data as name, lastname, typeUser and nControl, I want to print and a div for the user to see the details of your login.
Maybe I can be in JSON format but not how. I hope I have explained!!
// take username and password on button click
$('#submit').on('click', function(e) {
e.preventDefault();
var uname = $.trim($('input[name="username"]').val()),
password = $.trim($('input[name="password"]').val());
if(uname.length && password.length){ // checking that username and password not empty
$.ajax({
url : 'doLogin.php',
data: {username: uname, password: password},
dataType: 'json', // if you get response from server as json
success: function(response) {
// receive the response as json object
if(response.status == 'success') {
alert('You have been successfully authenticated');
/**
* assume that you get other
* data with response
*/
var name = response.name,
lastname = response.lastname,
typeUser = response.typeUser,
nControl = response.nControl;
// make navigation to dashboard.php with data you've got using GET method
// you may have need to location url as you need
window.location = 'dashboard.php?name=' + name + '&lastname=' + lastname + '&typeUser=' + typeUser + '&nControl=' + nControl;
} else {
alert('Error is authentication..');
}
}
});
} else {
// make alert if username or password not provided by user
alert('Please enter password and username both.');
}
});
Didnt have time to test. I dont have php on test server. You'll need the jquery.form.js plugin for JQuery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$('#loginbutton').click(function(){
$('#error').empty();
$('#loginform').ajaxForm(function(data, textStatus){
$('#error').append(data);
});
});
</script>
<div id="error"></div>
<form id="loginform" method="post" action="login.php">
<input type="text" name="username" />
<input type="password" name="password" />
<button id="loginbutton">Log In</button>
</form>
On login.php page check against database for correct username and password (my php is a little rusty)
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user' AND password='$password'");
$numrows = mysql_num_rows($query);
if ($numrows!=0)
{
//if row returned send them to home page
<script type="text/javascript">
window.location.replace("dashboard.php");
</script>
}
else
//If not correct login then the error div reports this message
echo "Incorrect Login Information";
}

Categories