PHP session not persistent with AJAX - javascript

I'm working on making a website (developing locally) that requires a login for users; I've used php-login.net framework as my starting point and have my code talking to MySQL and creating sessions just fine.
I've gone through most every SO question regarding php sessions and ajax; but I still can't get my code to work how I want.
Now, I'm using ajax to call some other php scripts after the user successfully logs in, however it's not working properly. In firefox, with all the cookies, history, etc cleared, it looks like the session variables aren't maintained with the ajax call. However, if I log-out and then log back in, the session variables seem to be passed properly across ajax.
For example:
In my logged_in.php script, I'm using ajax to call another script: view_samples.php.
logged_in.php
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButtons.js
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
url: "view_samples.php",
cache: false,
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>
When I log in with a browser that hasn't logged in before, I see it sets a session ID X; however when the button is pressed and the ajax call is made, I see a new session ID Y. I then log-out and log back in and see that my session ID is Y (before ajax) and that my session ID is Y when I click the button (after ajax).
I've also noticed that if I keep logging-in & out without pressing the view samples button, a new session id generated each time. However, as soon as I press the button, a whole new session id is created which seems to always be the one that is set if I log-out and then back in.
What am I missing? What's the proper way to go about ensuring the first session that is created is maintained throughout ajax calls? Should I POST the session id to the called script?

This is how I solved things (as Freaktor's comment above didn't resolve the issue) - I'm manually passing the session ID through AJAX and then setting it in the new PHP script. I'm wondering if anyone could comment on the security of this (as I'm not entirely sure how this all works)?
This and this post were helpful.
logged_in.php
<script>var session_id = '<?php echo session_id();?>';</script> <!-- store our session ID so that we can pass it through ajax -->
<script type="text/javascript" src="/js/loggedInButtons.js" > </script> <!-- all our ajax calls are here -->
<?php
// debug some variables
echo "<br>" . session_id() . "<br>";
// if logged in
if ($_SESSION['logged'] == 1) {
?>
<button class='btn btn-primary' id="view_samples"> View samples</button> <!-- calls view_samples.php -->
<div id="ajaxResult"></div> <!-- results of ajax calls go here -->
<?php
}
?>
loggedInButton.js
var data = {func:'getData1',session_id:session_id}; // manually send the session ID through ajax
$(document).ready(function(){
$("#view_samples").click(function(){
$.ajax({
type: "POST",
data: data,
url: "view_samples.php",
success: function(result){
$("#ajaxResult").html(result);
}
});
});
}
view_samples.php
<?php
session_id($_POST['session_id']); // get the session ID sent by AJAX and set it
session_start():
// debug session
print_r($_SESSION);
echo "<br>" . session_id() . "<br>";
if ($_SESSION['logged'] == 1) {
// do something because we are properly logged in
} else {
echo "not logged in!";
}
?>

Related

Redirect only after script Completes it's execution in codeigniter

I want to redirect to view with script in codeigniter. Script first and then page redirection.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function login()
{
$this->load->view('login');
}
}
I tried this code but it's not working because page is redirected before script completes it's executions. So, How to show notification in alert.
echo "<script>";
echo "alert('User not Found');";
echo "</script>";
redirect('home/login');
I tried with this also,
echo "<script>";
echo "alert('User not Found');";
echo "</script>";
echo "<script>setTimeout(\"location.href = 'http://localhost/dealsnow/index.php/home/login';\",300);</script>";
Second way is working for me but i think it's not good way. So is there any other option available for redirection to view after script completes it's execution.
Example : If i insert Form Data and then I want to show user that data is inserted properly in script and then i want the page to redirect.
Script first and then page redirection.
Solve my question,
If we want to execute script first and then after some timeout.
Ex. : if we want to show user that data is inserted properly in script and then i want the page to redirect.
echo "<script>";
echo "alert('Data Insereted Properly..!');";
echo "</script>";
$url = base_url().'/index.php/home/login';
header("refresh:3;url=$url");
use flash data in your code.
// Set flash data
$this->session->set_flashdata('error', 'User not Found');
// After that you need to used redirect function instead of load view such as
redirect("home/login");
// Get Flash data on view
$this->session->flashdata('error');
Hope it will help.

Trying to make php login work with Phonegap

I understand that for a login / register system to work within Phonegap, you have to use aJax with your php. I've got a sucessful php login and register page working but I'm unsure where to begin with jQuery / aJax a.k.a where I'm meant to put it, and what exactly I should be putting in. I was wondering if someone would know how to point me into the right direction.
jQuery
jQuery is a framework built on Javascript. Javascript is a client-side (browser) language . It runs on your device, unlike PHP that gets executed on the server.
You need to include jQuery in the HTML of your login page using script tags:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
jQuery provides a way to target any html element within your document and perform certain functions on that element. You specify what element by using the following syntax:
$(element).doSomething();
You can select classes or IDs:
<p id="myparagraph">A paragraph of text</p>
<p class="myparagraphclass">A paragraph of text</p>
$('#myparagraph').doSomething();
$('.myparagraphclass').doSomething();
AJAX
AJAX is a method introduced with Javascript that allows a page to request another url along with the result of that request. You will need to use AJAX login with Cordova/Phonegap because the "app" you're building is based on Javascript.
Thankfully, jQuery provides some really nice and easy to use AJAX methods.
Putting it together
I notice from a previous question that you have already created a PHP script that checks the login credentials are correct. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /public_html/access/login.php on line 15
I have edited slightly the code within that question (/access/login.php):
require_once($_SERVER['DOCUMENT_ROOT'] . "/html5up-aerial/access/functions.php");
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username&&$password) {
session_start();
require_once($_SERVER['DOCUMENT ROOT'] . "db_connect.php");
mysqli_select_db($db_server, $db_database) or
die("Couldn't find db");
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
*if($row = mysqli_fetch_array($result)){*
$db_username = $row['username'];
$db_password = $row['password'];
if($username==$db_username&&salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['logged']="logged";
//header('Location: home.php'); // Have commented this out
$message = "YOU ARE NOW LOGGED IN!"; // <- ADDED THIS
}else{
$message = "<h1>Incorrect password!</h1>";
}
}else{
$message = "<h1>That user does not exist!</h1>" .
"Please <a href='index.php'>try again</a>";
}
mysqli_free_result($result);
require_once("db_close.php");
}else{
$message = "<h1>Please enter a valid username/password</h1>";
}
//header/footer only required if submitting to a seperate page
echo $message; // ADDED THIS
die(); // ADDED THIS
This will be the PHP script that AJAX requests.
Now we create the HTML document with a login form and include jQuery and write our ajax code:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<form class="login-form" method="post">
Username: <input name="username" /><br />
Password: <input name="password" type="password" /><br />
<input type="submit" value="Login" />
</form>
<script>
$('.login-form').on('submit', function(e) { // Listen for submit
e.preventDefault(); // Don't actually submit the form
var data = $(this); // Put the form in a variable
$.ajax({
type: "POST",
url: '/access/login.php',
data: $(data).serialize(), // Make form data into correct format
success: function(response) {
alert(response); // Alert with the response from /access/login.php
}
});
});
</script>
To debug this code you will need to use Chrome development toolbar or Firefox Firebug. Hope this helps.

Sessions not setting using jquery and ajax

I have this code which uses jquery and ajax to send a request to the other page i.e.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<input type="button" id="butt" value="button11111111111111" >
</html>
<script>
$("#butt").on('click',function(e)
{
$.ajax(
{
type:'POST',
url:'testmysql.php',
data:
{
product_type:"cake";
}
});
});
</script>
When i click the above button it should send the request and data to the other file testmysql.php
<?php
session_start();
$_SESSION['type']=$_POST['product_type'];
echo $_SESSION['type'];
?>
However , when i refresh the other page after clicking the button i do not see any kind of echo and it gives me a notice stating
Undefined index: product_type
Since, i am new to ajax and jquery is there anything i am missing ?if yes,then what should i do to make this work ?
Thanks!
Note: Both of them are in the same directory.
First of all, remove the semicolon(;) from this statement,
product_type:"cake";
^
otherwise it will give you syntax error. And now comes to your issue.
when i refresh the other page after clicking the button i do not see any kind of echo and it gives me a notice stating Undefined index: product_type
That because when you refresh testmysql.php page, the $_POST array would be empty, and there would be no index named product_type in $_POST array. You can verify it using var_dump($_POST);.
On testmysql.php page you can check whether $_POST['product_type'] is set or not like this:
<?php
session_start();
if(isset($_POST['product_type'])){
$_SESSION['type']=$_POST['product_type'];
echo $_SESSION['type'];
}
?>
you added the ; at the end of the data object. remove it and try.
and you are sending a ajax request to the testmysql.php page, the $_POST['product_type'] will available when you are send the request. when you refresh the page the you are not sending any post request to testmysql.php page.

After redirect, how to display error messages coming from original file?

Here's what I'm trying to achieve: I want to redirect the user if any errors I check for are found to a html/php form (that the user see's first where inputs are previously created) with custom error messages.
Details: The User see's the HTML/PHP form first where they enter names in a csv format. After they click create, the names are processed in another file of just php where the names are checked for errors and other such things. If an error is found I want the User to be redirected to the HTML/PHP form where they can fix the errors and whatever corresponding error messages are displayed. Once they fix the names the User can click the 'create user' button and processed again (without errors hopefully) and upon completion, redirect user to a page where names and such things are displayed. The redirect happens after the headers are sent. From what I've read this isn't the best thing but, for now, it'll do for me.
Code For HTML/PHP form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
Activate: <input type="checkbox" name="activate">
</form>
<?php
// include 'processForm.php';
// errorCheck($fullname,$nameSplit,$formInputNames);
?>
</body>
</html>
I tried messing around with 'include' but it doesn't seem to do anything, however, I kept it here to help illustrate what I'm trying to achieve.
Code For Process:
$formInputNames = $_POST['names'];
$active = (isset($_POST['activate'])) ? $_POST['activate'] : false;
//checks if activate checkbox is being used
$email = '#grabby.com';
echo "<br>";
echo "<br>";
$fullnames = explode(", ", $_POST['names']);
if ($active == true) {
$active = '1';
//sets activate checkbox to '1' if it has been selected
}
/*----------------------Function to Insert User---------------------------*/
A Function is here to place names and other fields in database.
/*-------------------------End Function to Insert User--------------------*/
/*-----------------------Function for Errors---------------------*/
function errorCheck($fullname,$nameSplit,$formInputNames){
if ($formInputNames == empty($fullname)){
echo 'Error: Name Missing Here: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[0])) {
echo 'Error: First Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif ($formInputNames == empty($nameSplit[1])) {
echo 'Error: Last Name Missing in: '.$fullname.'<br><br>';
redirect('form.php');
}
elseif (preg_match('/[^A-Za-z, ]/', $fullname)) {
echo 'Error: Found Illegal Character in: '.$fullname.'<br><br>';
redirect('form.php');
}
}
/*-----------------------------End Function for Errors------------------------*/
/*--------------------------Function for Redirect-------------------------*/
function redirect($url){
$string = '<script type="text/javascript">';
$string .= 'window.location = "' .$url. '"';
$string .= '</script>';
echo $string;
}
/*-------------------------End Function for Redirect-----------------------*/
// Connect to database
I connect to the database here
foreach ($fullnames as $fullname) {
$nameSplit = explode(" ", $fullname);
//opens the database
I Open the database here
errorCheck($fullname,$nameSplit,$formInputNames);
$firstName = $nameSplit[0];//sets first part of name to first name
$lastName = $nameSplit[1];//sets second part of name to last name
$emailUser = $nameSplit[0].$email;//sets first part and adds email extension
newUser($firstName,$lastName,$emailUser,$active,$conn);
redirect('viewAll.php');
//echo '<META HTTP-EQUIV="Refresh" Content="0; URL=viewAll.php">';
//if you try this code out, you can see my redirect to viewAll doesn't work when errors are found...I would appreciate help fixing this as well. My immediate fix is using the line under it but I don't like it.
}
Any help is certainly appreciated.Thank You
Also it's worth noting I'm new to php. I would like to have an answer in php as well (if possible).
There's multiple ways of doing so. I personally would use AJAX. On a 'form submit', run a javascript function calling an AJAX request to a .php file to check the form information, all using post method. Calculate all the $_POST['variables'] checking for your defined errors. You would have an html element print the errors via AJAX request.
If there are 0 errors then in the request back return a string as so that your javascript function can look for if its ready to go. If ready to go, redirect the user to where ever you please.
AJAX is not hard and I only suggested the idea sense you put javascript in your tags.
Another method:
Having all your code on one .php file. When you submit the form to the same .php file check for the errors (at the top of the file). If $_POST['variables'] exist, which they do after you submit the form, you echo your errors in the needed places. If zero errors then you redirect the page.

Clearing notification onclick/toggle()

So I have a notifications system set up and it all works perfect except when I come to clearing the notification. Its clears ok when the div opens but it also clears if I refresh the page without the div been opened at all, I'm not wanting the notification to clear until the user has opened the notifications div. How would I go about doing this?
Any help or someone that could point me in the right direction will be greatly appreciated
Thank you
I have been using this line of code to clear the notification
<?php user_core::clear_notifications($user1_id); ?>
And this code is the OnClick toggle()
<div class="alert_header_item_container">
<a onclick="toggle('alert_dropdown');">
<div class="alert_header_item" id="alerts"></div>
<?
$sql = "SELECT * FROM notifications WHERE notification_targetuser=".$user1_id." AND notification_status = '1'" ;
$chant= mysqli_query($mysqli,$sql);
$num = mysqli_num_rows($chant);
if($num==1) {
echo '<div class="alert_header_item_new" id="alerts"></div>';
} else {
echo "";
}
?>
</a>
The issue you're having is this:
PHP does not load or execute Javascript. Here is an order of
execution:
The user requests data from your web server.
Your web server executes your PHP script, which outputs some HTML/Javascript.
The web server sends the HTML/Javascript to the user's browser.
The user's browser renders the HTML and executes the Javascript. So yes, the PHP will
finish executing before the Javascript is executed.
Basically your PHP is completed before you even toggle the onclick event.
What you really want to be doing is something like this:
Structure your HTML something like this.
<div class="alert_header_item_container">
<a id="read-notifications">
<div class="alert_header_item" id="alerts"></div>
</a>
</div>
Now we'd run an ajax request (when the document loads) to fetch the notifications
$(document).ready(function(){
$.ajax({
type: 'post',
url: 'notifications.php',
data: {id: user_id},
}).success(function(data){
$('alerts').html(data);
});
});
Which would call notifications.php where you'd run your php/sql to fetch the notifications:
<?php
$user1_id = $_POST['id']; // then sanitize as needed
$sql = "SELECT * FROM notifications WHERE notification_targetuser=" . $user1_id . " AND notification_status = '1'";
$chant = mysqli_query($mysqli, $sql);
$num = mysqli_num_rows($chant);
if ($num == 1) {
while($row = mysqli_fetch_assoc()){
// make notifications markup
}
echo MARKUP_FROM_ABOVE
}
?>
As for the onclick event, you'd do something like this (to a seperate php file that will update the notifications to set them to read (which is probably 0 ?)):
$(document).on('click', 'a#read-notifications', function(e) {
$.ajax({
type: 'post',
url: 'readnotifications.php',
data: {id: user_id},
}).success(function(data) {
// do what you need to do as notifications were read.
});
});
And on readnotifications.php you'd run an sql query that would update the notifications for $_POST['id'] (The user id) to 0 (read).

Categories