I have an ajax request that looks like this
$(document).ready(function() {
$(document).on('click', '#submit', function() {
var UserName = $('#username').val();
var PassWord = $('#password').val();
console.log(UserName);
$.ajax({
type: 'POST',
url: 'ajax/Login.php',
dataType: "text",
data: {
username: UserName,
password: PassWord
},
success: function(data) {
alert(JSON.stringify(data));
window.location='pages/mainpage.php';
},
error: function(data) {
alert('Login Error');
//window.location='../index.php';
}
});
});
});
and my php is like this
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
echo "Welcome ".$username;
}else{
echo "Password incorrect";
}
}
}else{
echo "Username is empty";
}
When i dont put anything in username i am expecting that the alert will be Username is empty same as when password is empty alert should be Password incorrect but i am getting "\r\n\" but if put some in username like John it will alert Welcome John"\r\n\" why is this happening?how to make it alert Username is empty when username is empty same with password?any idea is accepted..
Try this: in ajax section, dataType: "text", change to dataType: "json", and server php code is following: it may work
//put this function top of this page
ob_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$json="";
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
$json.="Welcome ".$username;
}else{
$json.="Password incorrect";
}
}
}else{
$json.="Username is empty";
}
ob_end_clean();
echo json_encode($json);
?>
I change isset to !empty fixed the problem
Related
I'm doing a login with ajax, html and php.
I've already debbuged the php, it's ok and it's returning the json variable I need in the ajax call.
I have this ajax function:
$(document).ready(function(){
$('#login').submit(function() {
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: 'login.php',
data: {
username: username,
password: password
},
type: 'post',
dataType: 'json',
success:function(response){
alert(response);
if(response.validacion == "ok"){
alert("Bienvenidos"),
localStorage.loginstatus = "true",
window.location.assign("home.php");
}
if(response.validacion == "error"){
window.location.assign("login.html"),
alert("Datos de usuario incorrectos, inténtelo nuevamente");
}
}
});
});
});
This is the login.php code: (I know it's really bad save password in cookies, but this is my solution for now)
<?php
session_start();
?>
<?php
include 'conexion.php';
if(isset($_POST['username'] && $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
}
$sql = "SELECT * FROM User WHERE username = '$username' OR Email ='$username'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
echo "Sesión abierta indefinidamente.<br/>";
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}mysqli_close($connection);
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
I did and inspect element, the username and password are ok, login.php is called, but when I continue the inspection from the line 20, this works until the line 25 aprox and skips to the line 44, the success:function(function) is skipped and the "response" variable is undefined but the login.php is returnint this variable ok:
What am I doing wrong? (sorry for my english, I'm spanish speaker)
Ok, I've solved the problem so I'm going to post what I've done for those who have the same problem:
the function success:function(response) is taking ALL the "echo" from the login.php, so the first "echo" when the login is ok, is the trouble and response become an undefined var.
When I post with the wrong credentials, I only have one echo (the json_encode) and I had not problem with the ajax. So the solution will be this, in the php, after the if(password_verify):
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}
mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
In order to get the value from the response, you need to JSON.parse() it first to allow your self to use response.validacion
Okay so I have an ajax function which sends data to register-process.php. I want the register-process.php to send the PHP value $msg back to ajax. I tried using $('.message').html("<?php $msg; ?>").fadeIn(500); on success but it does not seems to work. Is there any way to do it?
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var cpass = $("#cpass").val();
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val(),
cpass: $("#cpass").val()
};
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
$('.message').html("<?php $msg; ?>").fadeIn(500);
}
});
return false;
});
});
</script>
register-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
$cpass = (!empty($_POST['cpass']))?$_POST['cpass']:null;
$email = (!empty($_POST['email']))?$_POST['email']:null;
if($_POST){
$stmt = "SELECT COUNT(*) FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> execute();
$checkunm = $stmt->fetchColumn();
$stmt = "SELECT COUNT(*) FROM members WHERE mem_email = :email";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':email', $email);
$stmt->execute();
$checkeml = $stmt->fetchColumn();
if($uname == '' or $pass == '' or $cpass == '' or $email == ''){
$msg = "<div class='message-error'>Fields cannot be left empty. Please fill up all the fields.</div>";
}else if($checkunm > 0){
$msg = "<div class='message-error'>This username is already registered. Please use a different username.</div>";
}else if($checkeml > 0){
$msg = "<div class='message-error'>This Email ID is already registered. Please use a different Email ID.</div>";
}else if($pass != $cpass){
$msg = "<div class='message-error'>Passwords are not matching.</div>";
}else if(strlen($uname) > 12){
$msg = "<div class='message-error'>Username should not be more than 12 characters long.</div>";
}else if(strlen($uname) < 6){
$msg = "<div class='message-error'>Username must be at least 6 characters long.</div>";
}else if(strlen($pass) < 6){
$msg = "<div class='message-error'>Password must be at least 6 characters long.</div>";
}else{
// If everything is ok, insert user into the database
$stmt = "INSERT INTO members(mem_uname, mem_pass, mem_email)VALUES(:uname, :pass, :email)";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> bindValue(':pass', password_hash($pass, PASSWORD_BCRYPT));
$stmt-> bindValue(':email', $email);
$stmt-> execute();
if($meq){
$msg = "<div class='message-success'>Congratulations! You have been registered successfully. You can now login!</div>";
}else{
$msg = "<div class='message-error'>Server Error! Please try again later. If problem persists, please contact support.</div>";
}
}
}
echo $msg;
?>
In your Ajax function no need to echo the php variable.Just map response to your html element like below:
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
console.log(html);//see output on browser console
$('.message').html(html).fadeIn(500);
}
});
I would like to be able to have my form disabled from submitting when username is taken, and I would like to get some help with that.
my js code is:
$('#username').keyup(function() {
var username = $(this).val();
$('#username_status').html('Searching...');
if (username !='') {
$.post('username_check.php', { username: username}, function(data) {
$('#username_status').html(data);
});
} else{
$('#username_status').html('');
}
});
and my for checking username exists or not:
<?php
if(isset($_POST["username"]))
{
define("HOST","localhost");
define("USERNAME","root");
define("PASS","");
define("DBNAME","testingproject");
$connecDB = mysqli_connect(HOST, USERNAME, PASS, DBNAME)or die('could not connect to database');
$username = $_POST["username"];
$results = mysqli_query($connecDB,"SELECT id FROM attendant WHERE username='$username'");
$username_exist = mysqli_num_rows($results); //records count
if($username_exist) {
$output= "Sorry, this Username is taken";
echo ($output);
}else{
echo('available');
}
}
?>
on php page
if($username_exist) { echo 'yes'; }
else { echo 'no'; }
on js,
$.post('username_check.php', { username: username}, function(data) {
if (data == 'yes') {
// here disable the registration button
} else {
// active the registration button
}
});
hope it help!
also you can check this thread: JQuery/Ajax Post returned data and IF function
I wanted to do is connect some files in different folder inside elogFiles folder. My problem is i dont know how to connect the files inside of another folder files.
here is the family tree of my files:
http://s38.photobucket.com/user/eloginko/media/folder_zpsa156e2a5.png.html
My problem the links is not correct.
Both code are not related. And the user.php is asking for connection from inside the dbc folder database.php and myScript.js wants to find user.php where is located inside the view folder.
myScript.js: " url: 'js/../view/user.php',"
user.php: "include_once('view/../dbc/database.php');"
can anyone help me correct the correct directory links.
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
echo "1";
exit;
} else {
echo "Incorrect Email or Password";
}
}else{
echo "Please enter Email and Password";
}
?>
myScript.js
$(document).ready(function() {
$('div#show:empty').hide();
$('#login').click(function(){
var email = $('#lemail').val();
var password = $('#lpassword').val();
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'js/../view/user.php',
success: function(data)
{
if (Number(data) == 1)
{
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
}
else
{
$('div#show:empty').show();
$('#show').html(data);
}
}
});
return false;
});
});
As your hierarchy is presently, provided, if you are on your http://localhost/elogFiles/view/user.php, you just need to go level one up ../
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
$response['status'] = '';
$response['message'] = '';
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
$response['status'] = 'OK';
} else {
$response['status'] = 'ERROR';
$response['message'] = 'Username/Password not found';
}
}else {
$response['status'] = 'ERROR';
$response['message'] = 'Please input username/password';
}
echo json_encode($response);
exit;
?>
Since, user.php processes the AJAX request, point the AJAX url attribute to this file. Consider this example:
myScript.js
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'http://localhost/elogFiles/view/user.php',
dataType: 'JSON',
success: function(data) {
if (data.status == 'OK') {
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
} else {
$('div#show:empty').show();
$('#show').html(data.message);
}
}
});
I am working with php and MySQL my problem is how to make function or code in javascript that alerts users when selecting a user name that already exists and does not allow them to submit registration form.
thanks
I have done this using jQuery and PDO so it's an ajax username check
Here is my jQuery
$(document).ready(function() {
$('#username').keyup(function() {
var username = $('#username').val();
if(username == "" || username.length < 4) {
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
}
else{
$.ajax({
type: "POST",
url: "util/UsernameCheck.php",
data: 'username='+ username,
cache: false,
success: function(response) {
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}
else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
},
error: function(xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
});
});
The #tick and #cross are just images which are hidden/displayed depending if the username is being used.
The UsernameCheck.php
<?php
// your database info here
require '../config.php';
try {
// create a new instance of a PDO connection
$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
if(isset($_POST['username']) && !empty($_POST['username'])) {
$username = $_POST['username'];
$sql = 'SELECT username FROM users WHERE username = :username';
$stmt = $db->prepare($sql);
$stmt->bindValue('username', $username);
$stmt->execute();
$count = (int) count($stmt->fetchAll());
echo $count;
}
?>