im not so sure how this works, but where does my success(data) value come from?
must I return a value in url: php/login.php?
$.ajax({
url: 'php/login.php', //must i return a value in login.php?
data: {username:username,password:password},
type: "POST",
dataType: 'json',
success: function(data)
{
if(data == true){
console.log("sdfsdfs " + data);
login.submit();
}
else{
console.log("NO DATA PRESENT");
}
}
//else do an alert("please lgo in again");
});
in php/login.php i query the DB to see if such a user exists and if password match
part of my login.php
<?php
echo $username = $_POST['username']; //not echo-ing
echo $password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
if ($username&&$password) //check if the field username and password have values
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect=mysqli_connect($dbhost,$dbuser,$dbpass) or die("Unable to Connect");
mysqli_select_db($connect,"clients") or die("Could not open the db");
$sql = "SELECT * FROM clients.users WHERE username='$username'";
$login = mysqli_query($connect, $sql);
if (mysqli_num_rows($login))
{
while ($row = mysqli_fetch_assoc($login))
{
$db_password = $row['password'];
if ($password==$db_password)
{
$loginok = TRUE;
echo json_encode( true );
} else {
echo json_encode( false );
echo "Please re-enter username and password, they did not match";
header("Location: ../login.php");
}
?>
When you want to return some data using ajax, you need to echo data in your script that will be called by ajax. If the request is successful, it will return everything you echoed in your script into your parameter you specified in success function.
success: function(data)
{
// code...
}
so "data" will contain result from your script, then you can do whatever you want.
EDIT:
Well, i would solve it like this
$db_password = $row['password'];
if ($password==$db_password)
{
echo json_encode(array("status" => "ok", "message" => "Login successful!"));
} else {
echo json_encode(array("status" => "error", "message" => "Please re-enter username and password, they did not match!"));
//header("Location: ../login.php"); you don't need this
}
you can't echo json, then some text after it. You can, but it is not recommended at all.
Related
Is there a way to redirect the user with php file if the Session is empty?
for example this code:
pSession.php
<?php
include('pConfig.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($db,"select UserName from userinfo where UserName = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['UserName'];
if(!isset($_SESSION['login_user'])){
header("Location: ../login3.html");
die();
}
?>
and use it in javascript:
Javascript:
$(document).ready(function () {
checkSession();
})
function checkSession() {
$.ajax({
type: 'POST',
url: '../srtdash/php/pSession.php',
dataType: 'json',
data: '',
contentType: 'application/json; charset=utf-8',
success: function (response) {
console.log("Welcome to Credit Investigation");
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
}
HTML:
<script type="text/javascript" src="../srtdash/jsScripts/jsIndex.js"></script>
Am I doing it right to redirect if the User Actually logged on ? or if not How can I redirect the user to login.html if he/she is not logged in?
Make use of
<?php
include('pConfig.php');
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($sql);
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to Home page, " . $_SESSION['username'] . "!";
} else {
header("Location: ../login3.html");
}
?>
I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.
When the AJAX is called I always get these errors:
net::ERR_EMPTY_RESPONSE or net::ERR_CONNECTION_RESET
I also tryed different browsers (Chrome and Edge) but it is only working on localhost.
Thanks for all your help and support.
My PHP code (register.php):
require_once 'mysql_conn.php';
// username and password sent from form
$myUsername = mysqli_real_escape_string($db,$_POST['username']);
$myPassword = mysqli_real_escape_string($db,$_POST['password']);
$myRepPassword = mysqli_real_escape_string($db,$_POST['rep_password']);
if($myPassword == $myRepPassword && strlen($myUsername) >= 3 && strlen($myPassword) >= 8)
{
$userCheck = "SELECT id FROM users WHERE username = '$myUsername'";
$result = mysqli_query($db,$userCheck);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo "This user already exists";
}
else
{
$sql = "INSERT INTO users (username, password) VALUES ('$myUsername', '$myPassword')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
}
else
{
echo "Please check the values you inserted";
}
and the AJAX call:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register.php',
data: {username:username, password:password, rep_password:rep_password},
success: function (data) {
errorHandling(data);
}
});
});
});
I don't know how, but I solved it by deleting and re-creating the register.php file
I have a an ajax post method that if success will alert "account successfully created". my problem is when it's not created it should alert account already exists, But what the problem it still alert the same.
script code:
$(document).ready(function(){
$("#btn-register").click(function(){
var regaccount = $("#regaccount").val();
var regpass = $("#regpass").val();
if((regaccount == "") || (regpass == "")){
alert("Information required!");
}else {
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
alert("account successfully created!");
},
error:function(){
alert("account already exists");
}
});
}
$("#regaccount").val('');
$("#regpass").val('');
return false;
});
});
register.php
<?php
include 'function.php';
session_start();
ob_start();
$userid = rand(100000, 999999);
$regaccount = $_POST['regaccount'];
$regpass = $_POST['regpass'];
$regaccount = stripslashes($regaccount);
$regpass = stripcslashes($regpass);
$salt = "dctech2015ABcRXd";
$regpass = md5($regpass) . $salt;
$regpass = sha1($regpass);
$con = new Functions();
$con = $con->db;
$stmt = $con->query("SELECT * FROM users WHERE username = '$regaccount'");
$count = $stmt->rowCount();
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}else{
echo '<script>alert("account name already exists");</script>';
}
ob_end_flush();
?>
You need to do following changes to make this work:
1) In your PHP code, do not write any alert.
2) Whether user exists in database or newly inserted, AJAX request will fetch only data. We have to handle the logic.
3) AJAX error method will be called only when AJAX request is failed (either request not sent or response status is not 200 OK).
4) In your case, error method will never be called if user already exists or even user is inserted as data is being correctly transferred from JavaScript to PHP.
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
echo 'success';
}
else{
echo 'exists';
}
AND
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
if (data == 'success') {
alert("account successfully created!");
}
else if (data == 'exists') {
alert("account already exists");
}
},
error:function(){
alert("Unknown problem occured.");
}
});
Here you are trying to prompt message into AJAX error section which is wrong. You need to handle both into success section.
The very simple example is, return $count and check that value if greater then 0 means record is exist.
Changes in register.php code:
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}
echo $count;
I remove else part which is not require. And use $count for AJAX response.
And make correspond change into AJAX part also:
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
//If record exist...
if(data > 0){
alert("account name already exists");
}
else {
alert("account successfully created!");
}
},
error:function(){
alert("There is some error, Please try after some time OR contact site admin.");
}
});
Hope this is very easy to understand and help to other user also.
first of all I'm new with jQuery and PHP. My aim is to create a signup form, passing data to my server on wamp. My query is working, a new record is created in the database, but I can't figure out why it is showing the error log of the ajax call instead of the success one.
Ajax call
$('#reg-button').click(function(event){
$.ajax({
url: 'http://localhost:80/project/signup.php',
type: 'POST',
dataType: 'json',
data: {
email:$("#email").val(),
username:$("#username").val(),
password:$("#password").val()
},
error: function() {
console.log("error");
},
success:function(data){
console.log("success");
var responseData = jQuery.parseJSON(data);
}
});
event.preventDefault();
});
PHP
$response = array();
if (isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password'])){
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO user (email, username, password) VALUES ('$email', '$username', '$password')";
$result = mysqli_query($conn, $query);
if($result){
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
mysqli_free_result($result);
$response['success'] = 1;
$response['message'] = "User registered";
echo json_encode($response);
} else {
$response['success'] = 0;
$response['message'] = 'Ops, user not registered';
echo json_encode($response);
}
} else {
$response['success'] = 0;
$response['message'] = 'Required fields are missing';
echo json_encode($response);
}
Could you help me with fixing these problems, giving me some tips or tutorials?