I'm trying to check the existence of an username already registered on my application using jQuery+Ajax+POST.
HTML
<div class="form-group">
<label for="username" class="col-md-3 control-label">Username</label>
<div class="col-md-9">
<input type="text" id="username" class="form-control" name="username" placeholder="Username">
</div>
</div>
<div class="col-sm-9 col-sm-offset-3" id="userCheck">
<div class="alert alert-info" id="userCheckLabel"></div>
</div>
jQuery
$('#username').focusout(function() {
var username = $('#username').val();
checkUserExist(username);
})
function checkUserExist($uname) {
$.post( "../core/lib/checkUserExist.php", function( data ) {
if(data.html == 'true') {
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});
PHP
<?php
require_once('../../core/class.user.php');
$user = new USER();
$uname = $_POST['username'];
$stmt = $user->runQuery("SELECT user_nameFROM users WHERE user_name=:uname ");
$stmt->execute(array(':uname'=>$uname));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['user_name']==$uname) {
print 'true';
} else {
print 'false';
}
?>
I Don't include class.user.php cause It's only handling the PDO Connection, If I remove the if(data.html == 'true') the connection work as expected and the message come out.
Behavior
The code work if I remove the if(data.html == 'true'). but with this it doesn't do anything, no errors in console. So I think the error is in the way I handle the PHP part.
Any suggestion?
Since you are returning string not HTML, so you have to do like below:-
$.post( "../core/lib/checkUserExist.php",{username: uname }, function( data ) {
console.log(data);// check this and let me know the output
if(data == 'true') { // or try if(data)
$('#userCheck').slideDown("slow");
$('#userCheckLabel').text("This user already exist!")
}
});
Related
I am using PHP and Ajax to logging into another page with session variable. When I click submit button nothing happen.
The HTML code are following named as login.php:
<?php
require_once "dbconnection.php";
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: index.php");
exit;
}
?>
<div id='info'> </div>
<form method="POST" class="form-signin" name="mylogin" id="mylogin">
<div class="account-logo">
<img src="assets/img/logo-dark.png" alt="">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="email" name="email" autofocus="" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" id="password" class="form-control">
</div>
<div class="form-group text-right">
Forgot your password?
</div>
<div class="form-group text-center">
<input type="button" value="login" id="login" name="login"
class="btn btn-primary account-btn" >
</div>
<div class="text-center register-link">
Don’t have an account? Register Now
</div>
</form>
In the same page Ajax query is:
<script>
$(document).ready(function (){
$('#mylogin').validate({
rules: {
password:{
required:true;
},
email:{
required:true;
email:true
}
},
messages: {
password:{
required:"Requered"
},
email:"Requered"
},
submitHandler : subform
})
function subform() {
var email = $('#email').val();
var password = $('#password').val();
var data = {
"email": email,
"password": password
$.ajax({
type: "POST",
url: "auth/logging.php", // Url to which the request is send
data: data,
// Type of request to be send, called as method
beforeSend:function () {
$('#info').fadeOut();
$('#login').html('Sending ....');
},
success: function(resp){
if(resp=="ok"){
$('#login').html('Login');
setTimeout('window.location.href="index.php";',4000);
}else{
$('#info').fadeIn(1000,function(){
$('#info').html("<div class='alert alert-danger'>" +resp+ "</div>");
$('#login').html('Login');
})
}
}
})
}
})
</script>
My logging.php would be:
<?php
session_start();
require_once "dbconnection.php";
if (isset($_POST['email'])) {
$email = trim($_POST["email"]);
$pass = trim($_POST["password"]);
$password = md5($pass);
$query = $mysqli->prepare("SELECT * FROM users WHERE email=?");
$query->bind_param("d",$email);
$query->execute();
$query->bind_result($id,$user,$myemail,$mypass);
$query->fetch();
if($mypass==$password){
echo 'ok';
$_SESSION['id'] = $id;
$_SESSION['user'] = $user;
}else{
echo 'emai & pass wrog';
}
?>
Any help may appreciated.
It should be s instead of d. It stands for string.
$query->bind_param("s",$email);
Also you should never use MD5 for passwords. Use password_hash()
view: login.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
remember_me = $("#remember_me").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin,"remember_me":remember_me},
url:"<?php echo base_url(); ?>redirect",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect)
{
window.location.replace(data.redirect);
}
else
{
$(".login_success").html('<p>' + data.error + '</p>');
}
}
});
});
});
</script>
<div class="tab-pane" id="profile" role="tabpanel" data-mh="log-tab">
<div class="title h6">Login to your Account</div>
<form class="content">
<div class="login_success"></div>
<div class="row">
<input class="form-control" placeholder="" type="email" id="elogin">
<input class="form-control" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox">Remember Me
</div>
Login
</div>
</div>
</form>
</div>
controller:
public function login_redirect()
{
$email = $this->input->post('elogin');
$password = $this->input->post('plogin');
$remember = $this->input->post('remember_me');
if($email=='' || $password=='')
{
echo json_encode(array('error' => 'All fields are mandatory. Please fill all details.'));
}
else
{
$this->db->select('*');
$this->db->from('user');
$where = "email='".$email."' and password='".$password."' and status='1'";
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result_array();
$this->session->set_userdata('user_id',$result);
if (!isset($_POST))
{
header ("Location:".base_url()."thankyou");
}
else
{
echo json_encode(array('redirect' => base_url().'thankyou'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
}
In this code, I am creating a login module which works fine. Now, I also want to integrate the remember me option when user check remember me checkbox server ask to want to save detail or not. When user logout it doesn't require to fill it's detailed again inside the login form. Once the user checks on remember me checkbox. So, How can I do this? Please help me.
Thank You
You can make this by using cookie.
try following code:
//php (controller):
//after success login
if($remember){
//set cookie
$this->input->set_cookie('email', $email, 86500);
$this->input->set_cookie('password', $password, 86500);
}else
{
//delete cookie
delete_cookie('email');
delete_cookie('password');
}
view: login.php
//set cookie value if checked remember me.
<div class="row">
<input class="form-control" value="<?php if (get_cookie('email')) { echo get_cookie('email'); } ?>" placeholder="" type="email" id="elogin">
<input class="form-control" value="<?php if (get_cookie('password')) { echo get_cookie('password'); } ?>" placeholder="" type="password" id="plogin">
<input name="optionsCheckboxes" id="remember_me" type="checkbox" <?php if (get_cookie('email')) { ?> checked="checked" <?php } ?>>Remember Me
</div>
You can create the cookie with your javascript when you get the response of your ajax call. You should use document.cookie() if you choose this way to do.
If you choose the server side, CodeIgniter have a Cookie Helper. For use it, you have to add it 'cookie' on your autoload. You can load it with this line too :
$this->load->helper('cookie');
when the helper is loaded, you have to create the cookie in your controller like this :
$this->input->set_cookie('cookie_name', $value, time_in_seconds);
I am trying to check the entered username and email with the database to check its availability.
It checks the email perfectly fine. I am using the same code for the email but with different id tags:
Here is my form for username:
<label for="username">Desired Username</label>
<input type="text" class="form-control" id="desusername" name="desusername" placeholder="Enter username" onkeyup="checkname();" required>
<span id="name_status"></span>
Here is the function to check it:
function checkname()
{
var username=document.getElementById("desusername").value;
if(username) {
$.ajax({
type: 'post',
url: '../members/authentication/checkusername.php',
data: {
username:username,
},
success: function (response) {
$( '#name_status' ).html(response);
if(response=="OK") {
return true;
}else {
return false;
}
}
});
}
else {
$( '#name_status' ).html("");
return false;
}
}
And here is my php script to check:
<?php
require_once("../../includes/database.class.php");
if(isset($_POST['desusername'])){
$username = $_POST['desusername'];
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $database->query($sql);
if(mysqli_num_rows($result) > 0) {
?>
<div class="alert alert-danger" role="alert">
<strong>Username already exists</strong>. Please choose a different one.
</div>
<?php
}else{
?>
<div class="alert alert-success" role="alert" style="margin-top: 10px;">
<strong>Valid</strong>. You are good to go!
</div>
<?php
}
exit();
}
?>
Now, in the developers console it shows its calling the function everytime i type:
XHR finished loading: POST "http://localhost/members/authentication/checkusername.php".
But nothing is displaying in the relevant div (#name_status)..
You can't see the response because you're using the wrong index on checkusername.php.
change below code
if(isset($_POST['desusername'])){
$username = $_POST['desusername'];
to this
if(isset($_POST['username'])){
$username = $_POST['username'];
and you're good to go. :)
Make sure that
data: {
key:value,
},
You have to use key while fetching data from post request or get request.
I am trying to do a simple login through AJAX and it works fine except that after the success callback alerts the response, the browser shows the JSON response like this:
{"status":"success","username":1234}
I have used the same piece of code several times before with no problems, but I think I am missing some knowledge as to why this is happening? There are some modifications of course, but the AJAX part is the same in both PHP and Jquery and I can't figure out what I am doing wrong.
This is the Jquery:
$('#btnLogin').on('click', function(){
login();
});
function login(){
var un = $('#loginUn').val();
var pwd = $('#loginPwd').val();
$.ajax({
url: 'index.php?page=login',
type: 'POST',
dataType: 'json',
data: {'un': un, 'pwd': pwd},
success: function(data){
alert("You are logged in as "+data.username);
},
error: function (request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error+ " DATA: " + data);
}
});
}
The PHP controller:
include_once 'models/login.class.php';
$user = new Login( $dbh );
// If the form is submitted
if(isset($_POST['un'])){
// Check if fields are empty
$fields = array('un', 'pwd');
$error = false; //No errors yet
//Loop trough each field
foreach($fields AS $fieldname) {
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$error = true; //Yup there are errors
}
}
// If there are no errors
if(!$error) {
$un = $_POST['un'];
$pwd = $_POST['pwd'];
$user->checkUser($un, $pwd );
}
}
$view = include_once"views/login-html.php";
return $view;
And finally the model generating the response:
class Login {
private $dbh;
// Connect to database
public function __construct ( $pdo ) {
$this->dbh = $pdo;
}
public function checkUser ($un, $pwd ){
$sth = $this->dbh->prepare('SELECT password, username FROM employees WHERE username = ?');
$sth->execute(array($un));
//Getting the data from db
while($r=$sth->fetch()){
$password = $r['password'];
$username = $r['username'];
}
if($un == $username && $pwd == $password){
$array = array('status' => 'success', 'username' => $username);
// echo "<script>alert('You are logged in as ".$username."');</script>";
// echo "<script>window.location.href='index.php';</script>";
// echo json_encode(array('status' => 'success', 'username' => $username);
$forEcho = json_encode($array);
echo $forEcho;
}else{
echo json_encode(array('status' => 'failure'));
}
exit;
}// End checkUser function
}// End of class
This is the HTML:
<div class="container text-center">
<div class="col-sm-4 col-sm-offset-4">
<h1>Login</h1>
<form role="form" method="post">
<div class="form-group">
<div class="row">
<h3>Username</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-user"></span>
</div>
<input type="text" name="un" class="form-control" id="loginUn" placeholder="Please type in your username">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<h3 id="lblPassword">Password</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-key"></span>
</div>
<input type="password" name="pwd" class="form-control" id="loginPwd" placeholder="Please type in your password">
</div>
</div>
</div>
<button id="btnLogin" type="¨button" name="btnLogin" class="btn btn-success">Submit</button>
</form>
</div>
</div>
If somebody could tell me where I am going wrong I would really appreciate it! Have been looking for a solution/explanation with no result for several hours.
EDIT: Added the HTML. The alert in the success callback works just fine, but when closing it the JSON is all that is displayed on a blank screen. Never had this happen to me before.
You have an invalid value for the type attribute:
type="¨button"
… so the button reverts to the default and is a submit button.
You are seeing the results of submitting the form normally instead of using Ajax.
As a short term fix, remove the ¨. In the long term, you should adopt unobtrusive JavaScript as a best practise.
I bet btnLogin is a submit button, huh.. return false or prevent default to prevent the form from submitting..
$('#btnLogin').on('click', function(e){
e.preventDefault();
login();
});
I'm having an issue with AJAX/PHP form submission.
My ajax is as follows:
<script type="text/javascript">
$('#loginForm').submit(function() {
checkLogin();
});
function checkLogin()
{
$.ajax({
url: "login.php",
type: "POST",
data: {
username: $("#username").val(),
password: $("#password").val()
},
success: function(response)
{
if(response == 'true')
{
window.location.replace("main.html");
}
else
{
$("#errorMessage").html(response);
}
}
});
}
</script>
My form:
<form id="loginForm" data-ajax="false">
<label id="errorMessage"></label>
<div data-role="fieldcontain">
<label for="username">Username:</label>
<input id="username" type="text" placeholder="Username" />
</div><!-- End Contained Fields -->
<div data-role="fieldcontain">
<label for="password">Password:</label>
<input id="password" type="password" placeholder="Password" />
</div><!-- End Contained Fields -->
<div data-role="fieldcontain">
<input type="submit" id="login" value="Login" />
</div><!-- End Contained Fields -->
</form><!-- End Form -->
And then my login.php script:
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
if(!empty($username) && !empty($password))
{
$db = new PDO('mysql:host=localhost;dbname=mobile;charset=utf8', 'root', 'password');
try {
$stmt = $db->query("SELECT COUNT(*) FROM users WHERE username='$username' and password='$password'");
if(intval($stmt->fetchColumn()) === 1)
{
echo 'true';
}
else
{
echo 'false';
}
} catch(PDOException $ex) {
echo "An error has occured!";
}
}
?>
I originally had programmed my whole JQuery Mobile application using just raw php, but recently found out that I must use AJAX and Html to be able to port it to IOS and Android using PhoneGap.
I'm rather new to using ajax and have read as many articles that I could/topics here to try to get it to work. Unsure if I'm having a syntax issue or just not handling it correctly.
My local machine is loading a mysql server (database name is mobile, table I'm trying to load is users). I know that part is all correct because it works fine with php.
Could someone explain my issue? Thank you.
this:
$("$errorMessage").html("Attempting to login...");
should be:
$("#errorMessage").html("Attempting to login...");
or, if you have previously defined a $errorMessage variable like this:
var $errorMessage = $("#errorMessage");
it should be :
$errorMessage.html("Attempting to login...");
EDIT:
PHP manual : "For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement....."
you can try:
....
$stmt = $db->query("SELECT COUNT(*) FROM users WHERE username='$username' and password='$password'");
if (intval($stmt->fetchColumn()) === 1) { //make sure it's not a string
echo 'true';
$_SESSION['username'] = $username;
// OR perform another SELECT query to retrieve the data
}
else
{
echo 'false';
}
.....
The problem is this line:
window.location.replace('main.html');
Change it to:
window.location.href='main.html';