I'm trying to make an AJAX request, send the data to a PHP file, check if the username and password are correct, return an answer, and then run the login.php file which determines runs the session.
Right now, my AJAX request does nothing except print out my entire HTML code for the login page.
If someone knows why, please let me know...
(I apologize in advance for posting all of my login.js and checkLogin.php, I fear that the question may be unanswerable without the context for both)
This is login.js
$(function() { //Once the document has fully loaded
$("#login_form").submit(function(event) {
//INITIALIZING VARIABLES
var userName = $("#userName").val();
var passWord = $("#passWord").val();
var error = 0;
event.preventDefault(); //Prevent normal submit action
$("#userError, #passError").text(""); //Clear the text each time the user clicks submit
if (userName == "") { //Checking if the username is blank
$("#userError").text("Please enter your username");
error = 1;
}
if (passWord == "") { //Checking if the password is blank
$("#passError").text("Please enter your password");
error = 1;
}
//BEGIN Ajax Request
var $form = $(this),
term = $form.find("userName, passWord"),
url = 'checkLogin.php';
var posting = $.post(url, {username: userName, password: passWord});
posting.done(function(data) {
$("#userError").text(posting.responseText);
});
//END Ajax Request
if (error == 0) {
$("passError").text("Success");
}
}); //END submit button click
$("#login_form").submit();
});
This is checkLogin.php
<?php
$link = mysqli_connect(DB info private); //Database Connection
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //Keeps the text inside the this.responseText
//Preparing and Binding SQL statement
$stmt = mysqli_prepare($link, "SELECT username, password FROM login WHERE username =? and password =?");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
//PRINTS UNIDENTIFIED INDEX
$username = $_POST['username']; //Retrieving the username
$password = $_POST['password']; //Retrieving the password
mysqli_stmt_execute($stmt); //Execute the parameterized prepared statement
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
}
?>
Form tag from client_login.php
<form action="login.php" method="post" name="login_form" id="login_form">
</form>
You are not returning anything on checkLogin.php. You should try:
$row = mysqli_fetch_assoc($result);
if($row) {
echo "User found!";
exit();
}
I would recommend you, returning a text in json format. This way you can return more complex reponses to use in your js script. For example, in your checkLogin.php:
$row = mysqli_fetch_assoc($result);
if($row) {
echo json_encode([
'code' => '1', // code that represent successful
'message' => 'User found!'
]);
exit();
}
And in your login.js:
posting.done(function(data) {
var response = JSON.parse(data);
if(response.code == '1') {
$("#userError").text(response.message);
}
});
There are few issues here
url = checkLogin.php; should be url = 'checkLogin.php';
Right now url will be undefined and ajax url will post everything to yoursite.com/undefined and obiviosly the server will return 404 with default 404 page. Thats why you see html in your response.
YourcheckLogin.php should return some data to client. Use echo() for that.
Related
I've tried to verify if an email already exists in the database.
The same system worked perfectly if I tried to verify a username.
I'm using AJAX and PHP.
This is the file that gets the $_POST variables.
<?php
require_once 'Config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
$password = $_POST['password'];
if (!empty($password) and !empty($email)) {
$notEmpty = true;
include 'validate.php';
if($notEmpty == true and validateEmail($email) == true){
$password = md5($password);
$stmt = $link->prepare("INSERT INTO `Users`(`user_password`, `user_email`) VALUES (?,?)");
$stmt->bind_param("ss",$email,$password);
$stmt->execute();
}
}else{
$notEmpty == false;
}
}
?>
and this is the file that verifies the email doesn't exist on the database.
function validateEmail($user_email){
include '../Backend/Config.php';
$sql = "SELECT `user_password`, `user_email` FROM `Users` WHERE `user_email` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("s",$user_email);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$row = $result->fetch_assoc();
if ($result->num_rows > 0) {
echo 1;
return false;
}
else{
// echo json_encode(array('status' => 'OK'));
echo 0;
return true;
}
}
Js code(ajax):
$('#form').submit(function(e) {
//Don't refresh the page
e.preventDefault();
//Collecting data for the server call
post_data = {
'email' : $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
//AJAX server call to signup.php,which calls validate.php
$.ajax({
method: "POST",
url: "../Backend/signup.php",
data: post_data
})
//Server response and setting the input values to ""
.then(function( msg ) {
if(msg == 0){
console.log("Success, user data inserted. Code: " + msg);
}
//Failed
if(msg == 1){
console.log("Inserting failed. Error code:" + msg);
document.getElementById("error").innerHTML = "This email already exists.";
}
$('input[name=email]').val("");
$('input[name=password]').val("");
});
});
It inserts it anyway, what is the problem here?
If you immediately call num_rows() after executing a prepared statement, it will usually return 0 as it has no way to know how many rows are in the result set, since the result set is not saved in memory yet. You must first call store_result() to buffer the results so that the subsequent call to num_rows() will contain the correct results.
This is explained in the "User Notes" section at the bottom of the PHP documentation for num_rows().
how can I return a variable from a PHP query to AJAXA. I want the user to be redirected to the user panel using javascript after successfully entering the login and password. The query in PHP was successfully written but Ajax does not return any results.
Code Javascript:
$(document).ready(function() {
$("#btn-login").click(function() {
const loginAuth = $("#login-auth").val();
const passAuth = $("#pass-auth").val();
$.ajax({
type: "POST", //Request type
url: "http://localhost/game/login.php",
data: {
loginAuth: loginAuth,
passAuth: passAuth
},
cache: false,
success: function(data) {
console.log(data);
}
});
});
});
Code PHP:
<?php
require ('connect.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['loginAuth'])) {
// removes backslashes
$username = stripslashes($_REQUEST['loginAuth']);
// escapes special characters in a string
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_REQUEST['passAuth']);
$password = mysqli_real_escape_string($con, $password);
// Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE login='$username'
and password='" . md5($password) . "'";
$result = mysqli_query($con, $query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if ($rows == 1) {
$_SESSION['username'] = $username;
// Redirect user to index.php
$arr = 'udało się';
header("Location: panel.php");
}
else {
$arr = false;
header("Location: panelLogin.php");
}
}
else {
}
echo json_encode($arr);
?>
Thank you very much for every help.
you cannot redirect the user from the php script that is being called from ajax call.
because it will redirect but not on your browser instance but the ajax one.
you need to redirect it from javascript.
so you can do
echo "true";
instead of
header("Location: panel.php");
and echo "false"; // in case login failed
as an example but you can print some json text and use more informative messages
and you can check these values from ajax success function then you can do
window.location.href = "the url you want to redirect to";
I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.
I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.
How to POST values from submit and check if they exist in mysql?
And what do I have to type in my .php file?
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$('#login').submit(function(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
});
}
function getData(sendData) {
$.ajax({
type: 'POST',
url: 'http://www.url.php',
data: { 'username': username, 'password': password },
success: afhandeling,
});
}
Call ajax like this:
jQuery.ajax({
type: "POST",
url: "http://www.url.php",
data: { username:username,password:password },
success: function( data )
{
}
});
and in ajax file:
if (isset($_POST['username']) && isset($_Post['password']))
{
$query = "SELECT * FROM users WHERE username='".$_POST['username']."' AND password=".$_POST['password'];
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row)
{
echo 'login';
}
else
{
echo "error";
}
}
I think the URL has to be a local one, i.e. "/projects/blindchat/login.php".
On that page you can write something like this:
if (isset($_POST['username']) && isset($_POST['password'])) {
// MYSQL query:
SELECT 1 FROM users WHERE username = ? AND password = ?
}
Remember you have to escape the variables first to prevent SQL injection.
In login.php page you need to do something like this:
if(isset($_POST['username']) && isset($_Post['password'])) {
$q = "SELECT * FROM users WHERE username=$_POST['username'] AND password=$_POST['password']"
$r = mysql_query($q);
if(mysql_num_rows($r)==1) //Do Login
else echo "ERROR";
}
You submit the form which launches your ajax script that sends the data over to your PHP file that handles the input and gives you an answer.
Use PDO or MySqLi. Mysql is depreceated and no longer supported. My example below uses the PDO method.
Your PHP should look something like this(this is untested code, so there might be typos):
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
// We create a PDO connection to our database
$con = new PDO("mysql:host=yourhost;dbname=yourdatabase", "username", "password");
// We prepare our query, this effectively prevents sql injection
$query = $con->prepare("SELECT * FROM table WHERE username=:username AND password=:password LIMIT 1");
// We bind our $_POST values to the placeholders in our query
$query->bindValue(":username", $username, PDO::PARAM_STR);
$query->bindValue(":password", $password, PDO::PARAM_STR);
// We execute our query
$query->execute();
$result = $query->fetch(); // Grab the matches our query produced
// Here we check if we found a match in our DB
if (!empty($result)) {
echo "Matches were found";
} else {
echo "No matches found";
}
} else {
echo "Please fill out all fields";
}
?>
As for getting a reply from your AJAX script you can simply alert the response or show it as you please.
success: function(data) {
alert(data);
}