$_SESSION variable not setting in AJAX call - php

I wrote this call for user authentication:
$( '.sign-in' ).click( function(e) {
e.preventDefault();
var logincall = $.ajax({
type: "POST",
url: "../snippets/auth.php",
data: { username: $('#id_email').val(), password: $('#id_password').val() }
});
logincall.done(function( result ) {
alert( 'finished: ' + result );
if( result == 'valid' ) {
location.reload();
} else {
$( '.warning' ).toggleClass('hidden');
}
});
logincall.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
and here's the auth.php function
if( isset($_POST['username']) && isset($_POST['password']) ) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT COUNT(*) FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
if( $result['COUNT(*)'] !== 0 ) {
$_SESSION['logged'] = true; //this sets
$query = "SELECT id, level FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
$_SESSION['uid'] = $result['id']; //this DOES NOT set
$_SESSION['lvl'] = $result['level']; //this DOES NOT set
echo json_encode('valid');
} else {
echo json_encode('invalid');
}
}
The odd thing is, if I navigate directly to
myurl.com/snippets/auth.php?username=myusername&password=mypassword
it DOES set the other two session variables, but I can never get index.php to pick them up.
I even added that refresh line to it to ensure it could pick them up, and it gets $_SESSION['logged'] just fine, but not ['uid'] or ['level']

Related

AJAX: am I inserting data correctly?

I read many of the similar threads here to see what I'm doing wrong, but my AJAX call seems correct. What am I missing here? No alert is popping up, so I assume it's the JS side.
$("#SignupSubmit").click(function()
{
var fName = $("#txtSignFName").val();
var lName = $("#txtSignLName").val();
var email = $("#txtSignEmail").val();
var pw = $("#txtPW").val();
if( fName == "" || lName == "" || email == "" || pw == "" )
{
alert();
}
else
{
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
fName:fName,
lName:lName,
email:email,
pw:pw
},
success: function(response) {
alert(response);
}
});
}
});
And the PHP (is this correct?):
<?php
require "../connectionPages/localConnect.php";
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$email = $_POST["email"];
$pw = $_POST["pw"];
if($fName == null || $lName == null || $email == null || $pw == null)
$message = "missing required data";
else
{
$SQL = "INSERT INTO `customer/User` (custFName,
custLName,
custEmail,
custPassword)
VALUES ('$fName', '$lName','$email', '$pw')";
$mysqli->query($SQL);
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$SQL = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
$res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
json_encode($res);
}
else {
$message = "Unable to insert record: " . $mysqli->error;
}
$mysqli->close();
}
First phase update the below code in the data part.
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
And you are trying to get last inserted id. is it? if so use
$mysqli->insert_id;
instead of select query
Do this in AJAX
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
success: function(response) {
var res=eval(response);
alert(res.id);
}
});
And in your PHP page. Do this:
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$lastid = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
// $res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
echo json_encode(array('id'=>$lastid));
}
I hope it helps

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.

how to use user id stored in session with ajax

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()

php ajax login form

i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...

Checking if username exists in Database jQuery

I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my checkregister.php
header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}

Categories