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.
Related
I started learning php lately so i'm not so good with it. I've been trying to create a login system with php/ajax. I've tried all i could but can seem to figure out where the actual problem is coming from. Ajax couldn't get the data from my process.php file even though i already added it in the url. The only codes that get executed are those from the index script but nothing from process. My database connection is ok. Just that there seem to be no communication between ajax and process.php. It just executes the 'else'(data==true) code in Ajax instead. I'm sorry i may not be able to express myself very well but i just hope you understand what i mean.
Below are the files i created.
here is the member.php class
<?php
class member {
public $table;
public function __construct(){
$this->table = "users";
}
//login check
public function check($username,$password,$conn){
$this->table = "users";
//$password_hash = md5($password);
$stmt = $conn->prepare("SELECT * FROM ".$this->table." WHERE
Username='$username' AND Password='$password' LIMIT 1");
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
// print_r($row);
$_SESSION['id'] = $row['id'];
;
$_SESSION['email'] = $row['email'];
return true;
}
} else {
return false;
}
}
}
?>
here is the process.php file
<?php
session_start();
require_once('member.php');
//for login
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username ==""){
echo "Please enter your email";
}
elseif($password == ""){
echo "Please enter your password";
}
else{
//connect to database
require_once('db.php');
//instantiate the member class
$member = new member();
$login_check = $member->check($username,$password,$conn);
if($login_check == true){
echo true;
}
else{
echo "Invalid email or password";
}
}
}
?>
and here is the index file that contains the ajax code
<?php
//session_start();
include('header.php');
require_once('db.php');
require('process.php');
?>
<html lang="en">
<head>
<title>Login/Signup</title>
</head>
<body>
<div class="container">
<div class="content">
<div class="form">
<div id = "message"></div>
<ul class="tab">
<li>LOGIN</li>
<li>SIGNUP</li>
</ul>
<div class="tab-content">
<div class="login-tab">
<form id="login_form" method="post" class="login-
form" >
<div class="">
<input type="text" id = "username"
name="username" class="form-control" placeholder="Enter your Username">
</div>
<div class="">
<input type = "password" id = "password"
name="password" class="form-control" placeholder="Enter your Password">
</div>
<div><button type = "submit" id = "login"
name="login" class="btn btn-primary" >login</button></div>
</form>
<div class="clearfix"></div>
<p>Or Login with</p>
<ul class="alt-login">
<li><img src=""></li>
<li><img src=""></li>
<li><img src=""></li>
</ul>
</div>
<div class="clearfix"></div>
<div class="tab_signup">
<form>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$( document ).ready(function() {
$("#login").click(function(e){
e.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
var data = $("login_form").serialize();
$.ajax({
type : "POST",
url: 'process.php',
data : data,
success: function(data){
if(data==true){
$("#message").addClass('alert alert-success');
$("#message").html("Login successful");
$("#login").html('Redirecting..');
window.location ="dashboard.php";
}
else{
//alert(data);
$("#message").addClass('alert alert-danger');
$("#message").html('login failed');
$("#login").html('Failed');
}
},
error : function(jqXHR,textStatus,errorThrown){
if(textStatus ='error'){
alert('Request not completed');
}
$("#login").html('Failed');
},
beforeSend :function(){
$("#message").removeClass('alert alert-danger');
$("#message").html('');
$("#login").html('Logging in..');
},
});
// }
});
});
</script>
</html>
P.S i'm not bothering about hashing the password now cos i'm still test.
You are passing data using GET method in Ajax but using POST when retrieving data in process.php file. You need to change ajax calling code and should use post method. Also serialize function doesn't append login input element which you need to push manually. I have updated code and it will be like below:
$("#login").click(function (e) {
e.preventDefault();
var data = $("#login_form").serializeArray();
data.push({ name: this.name, value: this.id });
console.log(data);
$.ajax({
type: "POST",
url: 'process.php',
data: data,
success: function (data) {
if (data == true) {
$("#message").addClass('alert alert-success');
$("#message").html("Login successful");
$("#login").html('Redirecting..');
window.location = "dashboard.php";
} else {
$("#message").addClass('alert alert-danger');
$("#message").html('login failed');
$("#login").html('Failed');
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus = 'error') {
alert('Request not completed');
}
$("#login").html('Failed');
},
beforeSend: function () {
$("#message").removeClass('alert alert-danger');
$("#message").html('');
$("#login").html('Logging in..');
},
});
});
You can update your code as it is and it should work fine. Hope it helps you.
Please be patient because I know this question might have been answered but I have not been able to find it. I have been working on a project & lately I just started using AJAX.
My JSON is coming from PHP, which includes errors and success, now the issue is how do I access success(if the registrattion is successful to display as Text(not alert)) and display errors when registration fails.
What conditions should be used?
<div class="remodal" data-remodal-id="RegisterModal">
<div class="popup-1">
<div class="popup-content" id="register_container">
<div id="register_title" class="popup-title text-purple">Sign Up</div>
<div class="reg-notification">
<p>You Successfully registered to our website and now you can login and use our services</p>
Continue
</div>
<div id="json"></div>
<form id="register-form" action="register.php" method="POST">
<div class="form-grp">
<!--<label>Username</label>-->
<input type="text" id="username" name="username" placeholder="Username">
</div>
<div class="form-grp">
<input type="email" name="register_email" id="register_email" placeholder="Email">
</div>
<div class="form-grp">
<input type="password" id="register_password" name="register_password" placeholder="Password">
</div>
<div class="form-grp">
<input type="password" id="confirm_password" name="confirm_password" placeholder="Retype Password">
</div>
<div class="btn-grp">
<button type="submit" name="submit" class="button-purple" id="do_register">Sign Up</button>
<button class="button-white" style="margin-left: 30px;" data-remodal-target="LoginModal">Login to access</button>
</div>
</form>
</div>
This is my PHP below
if (strlen($password) >= 8 && strlen($password) <= 60) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$account->addUser($username, $password, $email);
if ($account->userExist()) {
$message['email'] = "Email Address Is Already Registered!";
} else {
$account->create();
$message['type'] = "success";
}
} else {
$message = 'Invalid email!, Please enter a valid Email';
}
header('Content-Type: application/json');
$response = ['message' => $message];
echo json_encode($response);
// echo json_encode($message);
//echo $message;
and this is my AJAX
$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
$("#json").html(data["message"]);
//response = response.slice(0, -1);
//response = JSON.parse(response);
//var json = JSON.parse(response);
//var resdata = response;
//var json = $.parseJSON(response);
//if (resdata) {
//alert(resdata['success']);
//alert(json['success']);
// $("#register-form").addClass("remove-form");
// $("#register_container").addClass("register-container-active");
// $("#register_title").html("Register was Successful");
// $(".reg-notification").addClass("show-reg-notification");
//}else if (resdata['email']) {
//alert(resdata['email']);
//}
//alert(json['email']);
//$("#msg").html(json.email);
//}
console.log(response);
},
error:function(error){
console.log(error);
}
});
As you can see all the codes I commented are failed codes, I like to display the message coming from PHP in my #json ID.
What I like to do is get the 'success' encoded from PHP to my HTML through AJAX, if user registration is successful, also get the 'email' error out if user exists.
I have no idea what condition to use in AJAX to test this or how to go about it and I know it will be something simple.
But I may be to clustered in the head to figure it ..as I keep looking at :(
You need to modify your php response first.
$response = [];
if (strlen($password) >= 8 && strlen($password) <= 60) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$account->addUser($username, $password, $email);
if ($account->userExist()) {
$response['type'] ="error";
$response['msg'] = "Email Address Is Already Registered!";
} else {
$account->create();
$response['type'] = "success";
$response['msg']="You are signed in successfully";
}
} else {
$response['type'] ="error";
$response['msg'] = 'Invalid email!, Please enter a valid Email';
}
echo json_encode($response);
}
//output
{"type":"success","msg":"You are signed in successfully"}
//ajax
$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
$("#json").html(data["msg"]);
//get the response type simply as data['type'] this will give you success or error
console.log(data);
},
error:function(error){
console.log(error);
}
});
$.ajax({
type: 'POST',
url: 'register.php',
dataType: 'json',
data: formData,
success: function (data) {
console.log(data.message.email);//that will print email already registered
var result=data.message.email;
if(result=="success"){
$("#json").empty();//incase it has previous data
$("#json").append(result);//that will append data in your div
}
else{
$("#json").empty();//incase it has previous data
$("#json").append(result);//that will append data in your div
}
},
error:function(error){
console.log(error);
}
});
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!")
}
});
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 using CodeIgniter for my web app and I'm currently stuck with AJAX forms.
I've made an view for my "forget password" modal and it looks like this:
<form action="<?=base_url()?>users/forgot_pass" method="post" id="forget_pass_form">
<div class="form_header">
<h1>Forgot your password?</h1>
</div>
<?php if($ajax_error == 0) { ?>
<div class="front_success">
<p>Password was succesfully sent to your email address.</p>
</div>
<?php } ?>
<?php if($ajax_error == 1) { ?>
<div class="login_error">
<p>Email address was not found in the database.</p>
</div>
<?php } ?>
<div id="loading_spinner"></div>
<p><input type="text" name="to_email" placeholder="Sähköpostiosoite" class="user" style="background-postion: -200px; margin-top: 20px;" />
<input type="submit" name="to_submit" value="Lähetä salasana" class="login_submit" id="forget-pass" /></p>
</form>
And here's my controller for it:
<?php
class Users extends CI_Controller {
public function forgot_pass()
{
if(isset($_POST['to_submit'])) {
$this->load->model('user');
$email = $_POST['to_email'];
$email_addr = $this->user->get_email_address($email);
if($email_addr) {
foreach($email_addr as $row) {
$this->load->library('email');
$this->email->from('me');
$this->email->to($email);
$this->email->subject('Testing');
$this->email->message('Your password is: ' . $row['password']);
if(!$this->email->send()) {
$data['ajax_error'] = 1;
} else {
$data['ajax_error'] = 0; }
}
}
}
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
}
?>
I won't post my Model since I know 100% sure it works and it only contains that one method to check if email is found in the database.
Now I want to make it more dynamic by using AJAX. I want it to echo the success message inside a div if the email address was found in the database and the mail was sent
to that email address, otherwise I want it to echo out the error "User was not found in the database".
Here's my js file which for now:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(){
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
}
});
return false;
});
});
The AJAX part itself is working, but I just don't know how to implement those messages. Any help would be much appreciated.
make your html code like this
<div class="front_success" style="display:none">
<p>Password was succesfully sent to your email address.</p>
</div>
<div class="login_error" style="display:none">
<p>Email address was not found in the database.</p>
</div>
small change in controller:-
if($this->email->send()) {
echo '1';
} else {
echo '0';
}
so what ever your controller return based on that success function will make the dive show
try to make you ajax code like this :-
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
},
success: function (data) {
//alert(data); alert it if you want to check the function output
if(data == '1'){
//if the email is send then it return 1 so that you show success msg
$("#login_success").show();
}else{
//if the email is not send then it return 0 so that you show error msg
$("#front_error").show();
}
$("#loading_spinner").hide();// hide when ajax complete
}
});