how to use user id stored in session with ajax - php

When the user login I am storing the userid into session and then I want to pass that user id to the ajax to retriever other information form the data base.
userid stored in session is not being passed to allResult.php
My login page code snippet where i make the session:
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password']))
{
$username1 = $_POST['username'];
$password1 = $_POST['password'];
$password2 = md5($password1);
$sql= "SELECT * FROM users WHERE userName='$username1' AND password='$password2'";
if($query_run = mysqli_query($conn, $sql))
{
$query_num_rows = mysqli_num_rows($query_run);
$stmt =mysqli_prepare($conn, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if($query_num_rows==1)
{
$row = mysqli_fetch_assoc($query_run);
$user_id = $row['id'];
$name=$row['Name'];
//creating session
$_SESSION['loggedin_time'] = time();
$_SESSION['userid'] = $user_id;
$_SESSION['name'] = $name;
}
}
else {
$msg = '*Wrong username or password';
}
}
Now after login the user will be taken to dashboard:
<?php
session_start();
include("functions.php");
if(isset($_SESSION["userid"])) {
if(isLoginSessionExpired()) {
header("Location:loginPage.php");
}
}
if($_SESSION['userid']=="" && $_SESSION['name']==""){
header("location: loginPage.php");
}
require 'dbconnect.php';
$userId = $_SESSION['userid'];
echo "$userId";
?>
in the dashboard i am trying to access the other data of the user with ajax
<script id="source" language="javascript" type="text/javascript">
$(function() {
$( "#tabs" ).tabs({active:0});
$.ajax({
url: 'allResult.php',
method:"POST",
data: ({uid:'$userId'}),
dataType: 'json',
success: function(data)
{
var date= data[0]['date'];
var time= data[0]['time'];
var ip= data[0]['ip'];
var lux= data[0]['lux'];
var press= data[0]['press'];
var acc_x= data[0]['acc_x'];
var acc_y= data[0]['acc_y'];
var acc_z= data[0]['acc_z'];
$("#tabs-1").html("<b>date: </b>"+date+"<b> time: </b>"+time+"<b> ip: </b>"+ip+"<b> lux: </b>"+lux+"<b> press: </b>"+press+"<b> acc_x: </b>"+acc_x+"<b> acc_y: </b>"+acc_y+"<b> acc_z: </b>"+acc_z);
} ,
error : function(request,error)
{
alert (error);
alert("Request: "+JSON.stringify(request));
}
});
});
I need to get the user id in order to run allResult.php
allResult.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'dbconnect.php';
$user_id = $_POST["uid"]
$sql_query = "SELECT * FROM data where id like '$user_id';";
$result = mysqli_query($conn,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$output [] = $row ;
echo json_encode($output);
}
else
{
echo "Error finding data..";
}
?>

Make all your user logged in data to be called into a json format.
Assuming you have all data under
somedomain.com/userData.php
<?php
#userData.php
if ($user == "loggedin") {
$data['name'] = $_SESSION[1]; //name
$data['email'] = $_SESSION[2]; //email
$data['extra'] = $_SESSION[3]; //etc.
echo json_encode($data, JSON_PREETY_PRINT);
}
?>
Then get data into realtime using jQuery Ajax.

Looks like you're missing session_start()

Related

Returning a variable from PHP to AJAX

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

Redirect not working properly while doing login

code:
<script>
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin},
url:"candidate.php",
success:function(data){
$(".login_success").html(data);
}
});
});
});
</script>
<div class="login_success"></div>
<form class="loginLay" id="myform">
<input type="text" name="elogin" id="elogin" class="form-control1" placeholder = "Enter Your Email"/>
<input type="text" name="plogin" id="plogin" class="form-control1" placeholder = "Enter Your Password"/>
Forgot Password
<center>
<input type="submit" name="login" id="login" class="btn btn-primary"/>
</center>
</form>
candidate.php
<?php
session_start();
include('config.php');
$email = $_POST['elogin'];
$password = $_POST['plogin'];
$sql = "select * from student where email = '$email' and password = '$password' and status = 'enable'";
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($result)
{
if ($num_rows > 0)
{
$sqls = "select * from student where email = '$email' and password = '$password'";
$results = mysqli_query($con,$sqls);
while ($rows = mysqli_fetch_assoc($results))
{
$_SESSION['student_id'] = $rows["id"];
}
header ("Location: student/dashboard.php");
}
else
{
echo "<p id='red'>Wrong email or password or may be your account not activated.</p>";
}
}
?>
I have created login form inside the bootstrap modal and wants to login using ajax but the problem is that when I click on login button it does't redirect to student/dashboard.php properly. This page i.e. student/dashboard.php are showing inside the model. I do't know why what is the problem. So, How can I redirect in student/dashboard.php ?Please help me.
Thank You
try this
<?php
session_start();
include('config.php');
$email = $_POST['elogin'];
$password = $_POST['plogin'];
$sql = "select * from student where email = '$email' and password = '$password' and status = 'enable'";
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($result)
{
if ($num_rows > 0)
{
$sqls = "select * from student where email = '$email' and password = '$password'";
$results = mysqli_query($con,$sqls);
while ($rows = mysqli_fetch_assoc($results))
{
$_SESSION['student_id'] = $rows["id"];
}
if (!isset($_POST)) {
header ("Location: student/dashboard.php");
} else {
echo json_encode(array('redirect' => 'student/dashboard.php'));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
}
?>
JS:
<script>
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
elogin = $("#elogin").val();
plogin = $("#plogin").val();
$.ajax({
type:"POST",
data:{"elogin":elogin,"plogin":plogin},
url:"candidate.php",
success: function(data) {
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect) {
window.location.replace(data.redirect);
} else {
$(".login_success").html('<p id="red">' + data.error + '</p>');
}
}
});
});
});
</script>
Sam,
A proper way is to redirect it from client side instead of redirecting it through server.
It wont work in this case.
Try to send some response from server and depending upon that do a redirect through window.location.href.
You need to maintain a value in session after logging in and in dashboard check the value.

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.

Managing users view profiles system and passing the id to view profile page to display correct avatar image

Im trying to set up user environment system. I have home.php page which is a profile page and planet_search.php which displays all users with ability to view their profiles. I'm struggling on passing the id variable to home.php, so I can show correct avatar image.Here the part of home.php that displays avatar image:
<img class='ima'src="<?php
$id = $_SESSION['id'];
$query = "SELECT avatar_url FROM users WHERE id = '$id' LIMIT 1";
if(isset($_POST['id'])){$idu = $_POST['id'];
"SELECT avatar_url FROM users WHERE id = '$idu' LIMIT 1";}
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_assoc($result);
if(!$row["avatar_url"]){echo 'img/profile3.png';}else{echo $row["avatar_url"];}
?>" alt="face" >
And here is JQuery from planet_search.php:
$(document).ready(function() {
$('.square').on('click', function(){
$this_id = $(this).find('.id_user').text();
$.ajax({
type: "POST",
url: "home.php",
data: { id: $this_id }, // or the string: 'id=1'
complete:
function () {
window.location = "home.php";
}
});
})
});
BUt it doesnt work? it doesnt pass the variable because the
if(isset($_POST['id']))
is never true. What am I doing wrong?
Try to use this code instead.
<?php
$idu = null;
if (isset($_GET['id'])) {
$idu = $_GET['id'];
} elseif (isset($_SESSION['id'])) {
$idu = $_SESSION['id'];
}
$avatar_url = "img/profile3.png";
if (!is_null($idu)) {
$query = "SELECT avatar_url FROM users WHERE id = '$idu' LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if ($row["avatar_url"]) {
$avatar_url = $row["avatar_url"];
}
}
?>
<img class='ima' src="<?php echo $avatar_url; ?>" alt="face">
and JS:
$('.square').on('click', function () {
$this_id = $(this).find('.id_user').text();
if ($this_id != "") {
window.location = "home.php?id=" + $this_id;
}
});
you didn't start a session, session_start();

how to get json response in ajax?

url : http://localhost/test-mobile/log.php?username=&password=pass
$.ajax({
url:url,
type:'POST',
data:{message:message},
dataType:'json',
json:'members',
success:successData,
error:function(){
alert("error")
}
});
function successData(data){
var response=data.message;
alert(response);
}
json response is {"members":{"httpCode":"400","message":"Username missing"}}
PHP code is given below:
<?php
require_once("class/clsdatabase.php"); //Connect to SQL
$username = $_GET['username'];
$password = $_GET['password'];
//Check Username
if($username == '') {
$user = 'Username missing';
$success = true;
$status = array("httpCode"=>"400", "message"=>$user);
//return $status;
}
//Check Password
if($password == '') {
$pass = 'Password missing';
$success = true;
}
//Create SELECT query
$qry = "select * from user_register where emp_code='$username' AND emp_password='$password' AND active='1';";
$result = mysql_query($qry);
$te = mysql_num_rows($result);
if($te == 0 && $username != '' && $password != '') {
$both = 'Invalid username or password';
$success = true;
}
//If there are input validations, redirect back to the registration form
if($te != 0 && $username != '' && $password != '') {
$row = mysql_fetch_assoc($result);
$name = $row['emp_code'];
$success = true;
$status = array("httpCode"=>"400", "message"=>$name);
//return $status;
}
//echo $_GET['callback']. '(' . json_encode($status) . ');';
echo '{"members":'.json_encode($status).'}';
?>
alert a json response
I would split the pages up into two. One file called ajax.php and another called index.php.
Your index.php will look something like.
<html>
<head>
<script type="text/javascript">
postData={ajax:"testing",id:'123'};
$.post('ajax.php', postData , function (data) {
alert(data);
});
</script>
</head>
<body>
</body>
</html>
And your ajax.php file will look something like
<?php
// its important that this file only outputs json or javascript
// content and nothing else.
if(isset($_REQUEST['ajax'])){
$ajaxRequest = $_REQUEST['ajax'];
if($ajaxRequest == 'testing'){
// do some php stuff here -- if you look at the above example we sent an id variable
$sql = "SELECT FROM table WHERE id = {$_REQUEST['id']}";
$results = query($sql);
echo json_encode($results);
exit; // exit the script here so that only the ajax stuff is output
}
}
The jQuery .ajax function automatically decodes the JSON object if the dataType:'json' parameter is set (which it is in his query). So the 'data' variable passed to the success() function will already be a javascript object.
To access the 'message' value, you would use "data.members.message" since the 'members' object contains the 'message' value.

Categories