Returning a variable from PHP to AJAX - php

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";

Related

Why does my AJAX request print out the pages entire HTML code?

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.

How to get php session data from a google sign in

I am trying to create a website where users login with their google login (https://developers.google.com/identity/sign-in/web/sign-in). The site has multiple pages and gets data for the user from a mysql database. I would like to store the users' data (name, email) in a php session to have ready for the php when accessing the database. The login function works, but I can't figure out how to get the data to php, with it currently all in javascript.
There wasn't a conventional way to do this, but I was able to get the information from the google auth token
function get_var($var_index) {
$id = $_POST["id"];
$id_token = file("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id);
$var = str_replace("\"", "", $id_token[$var_index]);
$var = str_replace(",", "", $var);
$var = substr($var, strpos($var, ":") + 2 );
return $var;
}
$name = get_var(12);
$email = get_var(5);
$img_url = get_var(13);
$exp = get_var(8);
$iss = get_var(9);
if ($_SERVER['REQUEST_TIME'] < $exp) {
session_start();
$_SESSION["name"] = $name;
//$_SESSION["imageurl"] = $img_url;
$_SESSION["email"] = $email;
$_SESSION["exp"] = $exp; // when to auto logout
header("LOCATION: page.php");
exit();
} else{
header("LOCATION: loginpage.html");
}
You can use ajax for this. It's a very efficient way. just make sure you have jquery uncmopressed or minified (not slim) in you page and you're good to go.
This my javascript code in my page where the button is:-
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
$.ajax({
type: "POST",
url: "googlesignin.php?action=google",
data: "gmail=" + profile.getEmail() + "&name=" + profile.getName(),
success: function(result) {
if (result == 1) {
alert("Hello, " + profile.getName());
$("#googlesignin").hide();
} else {
alert("failed to login");
}
}
})
}
So now the new file called googlesignin.php from where you will execute the insert query to the mysql database
if ($_GET['action'] == "google") {
$email = $_POST['gmail'];
$name = $_POST['name'];
$query = "SELECT * FROM google WHERE email='".$email."' AND name='".$name."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo 1;
} else {
$query = "INSERT INTO google (email, name) VALUES ('".$email."', '".$name."')";
$result = mysqli_query($link, $query);
echo 1;
}
}
so now we have stored our post variables as php variables and we can use them easily to execute our insert query. but we need to check whether the email has first registered or not.

set php session on success of ajax

I have problem .i am making ajax call to a php file that will check credentials, if true i want to redirect to page , but if false i want to show error. I have little bit problem . Here is my code ajax Code.
function Login(val1, val2) {
alert(val1 + "\n" + val2);
$.ajax({
type: "POST",
url: "login.php",
data: 'username='+val1+'&password='+val2,
success: function(data) {
alert(data);
if(data=="true"){
window.location.replace('./admin/index.php');
}else
$("#Area").html(data);
}
});
and this is my php code.
<?php
require_once '/admin/DbHelper.php';
if (isset($_POST['password'])) {
$pass = $_POST['password'];
$name = $_POST['username'];
$query = "select * from user_login where userName='$name' and userPass='$pass'";
$result = mysqli_query($link, $query);
$row= mysqli_fetch_array($result);
if ($row > 0) {
$_SESSION['userName'] = $name;
echo "true"; } else {
echo '<label style="color:red"> Invalid User Name or Passowrd !</label>';
}
}
i can't understand where i should set session. please help me.

Returning AJAX Success and Error

I have built a login script that uses AJAX to submit form data.
The PHP part works fine without AJAX. But the system doesnt work with AJAX Implementation.
It always Displays the below message even though the PHP file returns true[correct username & password] ... Seems like the if condition in Jquery is not working.
Incorrect Username/Password
HTML Result Div
<div id="user-result" align="center"></div>
Jquery
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data == "true") {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>
fn_login.php
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo "true";
}
else {
die();
}
}
}
?>
Can someone please point out the mistake in the code/practice.
EDIT
Just Tried disabling AJAX, the PHP file works correctly echoing true when username/pass is correct
You have spaces after ?>
So, the AJAX response is having spaces after true.
Solution:
Remove ?> from the end of PHP file.
It will not affect any PHP functionality.
And you AJAX response will be without spaces.
Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.
Tips for debugging AJAX:
1) Always use Firefox (with Firebug Add) on Or Chrome.
2) Use Console tab of Firebug, to check which AJAX requests are going.
3) Here, you can see input parameters, headers and most important response.
4) So, in short you can debug a whole AJAX request life cycle.
You can echo json_encode(array('success'=>true)) from php code and modify your if condition in jquery with if(data.success){} Your modified code becomes
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo json_encode(array('success'=>true));
}
else {
die();
}
}
}
AND JQuery becomes
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data.success) {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>

How to: Ajax check values in php/database

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

Categories