Ajax is skipping success:function call - javascript

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

Related

JSON/PHP/MYSQL login connection error

I'm new to PHP programming and I'm trying to test out a login page alongside JSON and MySQL. I managed to make most of it functional but I can't seem to find a way to make the query in which I verify the username and password to work.
Please help.
Here's the code:
login.js:
$(document).ready(function(){
$('#errorLogin').hide();
$('#formLogin').submit(function(e){
var username=$('#inputUser').val();
var password=$('#inputPassword').val();
$.ajax({
type:'get',
dataType: 'json',
url: 'dist/php/connection-login.php',
data: {
user: username,
pass: password
},
success: function(e){
console.log(e);
}
});
});
});
connection-login.php:
<?php
$con = new mysqli("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$result = mysqli_fetch_assoc($qry);
$row = mysqli_fetch_assoc($result);
if ($row != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
Your PHP should be more like:
connect.php - make sure this is a separate secure page
<?php
function db(){
return new mysqli('localhost', 'root', 'root', 'solucionar_manutencoes_db');
}
?>
I would change your JavaScript AJAX to a POST request, unless you have a reason for it.
connection-login.php
<?php
sesson_start(); include 'connect.php';
if(isset($_POST['user'], $_POST['pass'])){
$db = db(); $r = array();
$prep = $db->prepare('SELECT `lg_user` FROM login WHERE `lg_user`=? && lg_user=?');
$prep->bind_param('ss', $_POST['user'], $_POST['pass']); $prep->execute();
if($prep->num_rows){
$prep->bind_result($lg_user); $r['user'] = $lg_user;
$_SESSION['logged_in'] = $lg_user;
}
echo json_encode($r);
}
?
Now if your JavaScript AJAX result does not contain the a e.user then they are not logged in. Of course, you would probably want to store the original password as a SHA1 or stronger and use AES_ENCRYPTION or better for Personal Information, along with SSL.
I see several errors in your code. The first is that you are executing mysqli_fetch_assoc twice: once on the result, and then again on the array the first call returned. The next is that the $response variable was never declared. Here is the fixed PHP script:
<?php
$con = mysqli_connect("localhost", "root", "root", "solucionar_manutencoes_db");
$lg_user=$_GET['user'];
$lg_password=$_GET['pass'];
if (mysqli_connect_errno()) trigger_error(mysqli_connect_error());
$qry = mysqli_query($con, "SELECT * FROM tb_login WHERE lg_user = '$lg_user' AND lg_password = '$lg_password';");
$results = mysqli_fetch_assoc($qry);
$response = [];
if (count($results) != 0) {
$response["success"] = 1;
echo json_encode($response);
}
else {
$response["failed"] = 0;
echo json_encode($response);
}
?>
In your JavaScript make sure to use e.preventDefault() inside #formLogin's submit handler to prevent page reload when that form is submitted.

PHP Header redirect not working anymore when i use event.preventDefault() on submit

my PHP code was working fine until I decided to use jquery for my signup page to handle and check the fields, it's working there is no error, everything is submitted to the server correctly so there is no problem with the code PHP nor jquery, but the header("location: ../****.php") no longer send me to another page after I hit submit, instead it loads the new page on top of the old one without refreshing.
This is my jquery code for the signup page:
<script>
$(document).ready(function() {
$("#myForm").submit(function(event){
event.preventDefault();
var username = $("#signup-username").val();
var pwd = $("#signup-pwd").val();
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
});
});
</script>
and this is my PHP code in my include page:
<?php
if (isset($_POST['submit'])){
include_once 'dbh.inc.php';
$username= mysqli_real_escape_string($conn, $_POST['username']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = $errorValid = false;
if(empty($username)|| empty($pwd)){
echo "Fill in all Fields!";
$errorEmpty = true;
}
else{
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uid);
$uid = $username;
$stmt->execute();
$result = $stmt->get_result();
$usernamecheck = mysqli_num_rows($result); // check if the results
$rowNum = $result->num_rows;
if($rowNum > 0){
echo "Username is taken!";
$errorValid = true;
}
else{
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, pwd) VALUES (?, ?)");
$stmt->bind_param("ss",$uid, $password);
$uid = $username;
$password = $hashedPwd;
$stmt->execute();
$result = $stmt->get_result();
header("location: ../user-login.php");
}
}
}else{
header("location: ../user-signup.php");
exit();
}
?>
<script>
$("#signup-username, #signup-pwd").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorValid = "<?php echo $errorValid; ?>";
if (errorEmpty == true $$ errorValid == true){
$("#signup-username, #signup-pwd").addClass("input-error");
if (errorFEmpty == false && errorValid == false){
$("#signup-username, #signup-pwd,").val("");
}
</script>
how do I fix this?
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
When the above code gets to the point where header("Location: file.php");
It'll fetch that file into $(".form-message")
To Avoid this you can use ajax to post data and javascript inbuilt redirection
$.ajax({
type: "POST",
url: "includes/user-signup.inc.php",
data: "username="+ username +"&pwd="+ pwd,
success: function(data) {
window.location.href = "../****.php";
}
});
Hope this answer was helpful.
Your code operates exactly as it should.
$(document).ready(function() {
$("#myForm").submit(function(event){
// THIS LINE RIGHT HERE
event.preventDefault();
******************
$(".form-message").load("includes/user-signup.inc.php",{
******************
});
});
});
Event prevent default stops the redirect action. Additionally you then use jquery to load the contents of the file into the DOM element with the class:
.form-message
Remove event.preventDefault();

Throw PHP variable back to Ajax on submit form data

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);
}
});

PHP/JS: cannot get

All I want to do is print 'win!' if they log in with their details in the Database (working correctly) and 'loss' if for some reason their info was not found in the DB.
So my issue is that for some reason my line of code 'echo $email;' doesn't work. It seems be set to NULL.
At the moment it only ever prints 'loss' regardless what i enter, but, if I add a row in the database that has a blank email and password (email = "", password="") then the php script returns 'win!'.
PHP CODE:
<?php
// echo "php test";
//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";
//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
//Check connection for failure
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Read in email & password
echo "reading in email & password...";
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']);
echo $email; //this prints blank
echo $password; //this also prints blank
$sql = "SELECT Name FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
echo "win!!";
} else {
echo "loss";
}
mysqli_close($conn);
?>
JS CODE:
$(document).ready(function(){
// alert("js working");
$('#login_button').click(function(){
var email = $('#email').val(); //prints the correct value
var password = $('#password').val(); //prints the correct value
var dataString = 'email1=' + email
+ '&password1=' + password;
$.ajax({
type: "POST",
url: "http://localhost:8888/php/login.php",
data: dataString, //posts to PHP script
success: success()
});
});//eo login_button
function success(){
alert("success");
}
});//eof
Apart from the fact that that is completely, insanely useless and with no security whatsoever, you can just exchange $.ajax() for $.post() and do like this:
var loginEmail = $('#email').val();
var loginPassword = $('#password').val();
$.post('login.php',{email:loginEmail,password1:loginPassword},function(data) {
console.log(data);
})

"\r\n\" in alert for jquery ajax html

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

Categories

Resources