session variable not set first time but if reloaded it is set - javascript

I have 2 files.
Home.php
some_func.php
I am setting a session variable in home.php and I am having an ajax call to some_func.php on button click.
Issue:
When I load the page for the first time, the session variable is set in home.php but the same is not reflected in some_func.php and if I reload home.php and then after that the session variable value is reflected in some_func.php.
I don't know why the session variable value is not getting reflected when I load home.php for the first time.
I have found that this is happening only on my live server and not on my localhost.
Please help.
<?php
//home.php file
session_start();
include 'db.inc.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die('Unable to connect. Check connection parameters');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
//Checking what is the latest session id available available in my db.
$query = "SELECT max(ses_id) as max_ses_id FROM `dyn_sess` ";
$result = mysql_query($query, $db) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$_SESSION['curr_sess'] = $row['max_ses_id']+1;
}
echo '<script> alert("Your Session ID : '.$_SESSION['curr_sess'].'");</script>';
?>
<html lang="en">
<head>
</head>
<body>
<meta charset="utf-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function call_some_func()
{
$.post('some_func.php');
}
</script>
<input type="button" value="PREV" onClick=call_some_func()>
</body>
</html>
<?php
//some_func.php
session_start();
require_once('lib/something.php');
// some php code here.
// No sessions variable are set. But the session variable curr_sess is used to call an api and that goes as blank for the first time.
//If I reload home.php it works fine then after from the second time.
?>
<html>
<script> alert(<?php echo $_SESSION['curr_sess'] ?>); </script>
</html>

Related

Update content with Ajax. How to separate the output in HTML <div>

I am updating my site content with AJAX by using this method i have found here: https://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
This works very well but according to this tutorial i have to echo the values i want to show as an updated value in the background running "record_count.php". Later all values are shown up in my frontend file "index.php" within the specific <div id="xxx">. my problem is now that in my background "record_count.php" i have several values i echo but in need them in separate HTML <div id="1, 2, ...> In my example it is $name and $city. How can i connect the values to a specific HTML <div id="1, 2, ...> ? (Please ignore the old query method i have copy/paste here. In my code i am using prepared statements with PDO)
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $id; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
<body>
<div id="load_tweets"> </div>
</body>
</script>
record_count.php
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select name, city FROM users where id = $id");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $city;
echo $name
?>

Passing php objects to Javascript without exposing php object values in page source

I have an index.php, a navbar.php landingpage.php, and a landingpage.js
The navbar.php file is where I retrieve user information upon successful login on index.php As shown below, I use if-else to select which navigation items to display per user. In this case, we have Settings navigation item.
navbar.php
<?php
require_once 'core/init.php';
require_once 'dbutil/dbconnection.php';
require_once 'functions/sanitize.php';
require_once 'functions/redirect.php';
$user = new User();
$user->setId($_SESSION['userId']);
$user->setUsername($_SESSION['username']);
$user->setPassword($_SESSION['password']);
$user->setLastname($_SESSION['lastname']);
$user->setFirstname($_SESSION['firstname']);
$user->setMiddleinitial($_SESSION['middlename']);
$role = new Role();
$role->setRoleId($_SESSION['roleId']);
$role->setRolename($_SESSION['rolename']);
?>
<?php if ($role->getRolename() === 'Administrator') : ?>
<a class="nav_tab" id="admin_settings" href="#">
Settings
</a>
<?php endif; ?> ....
landingpage.php has the navbar.php attached to it.
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<!-- this div gets filled with different content/page depending on what was clicked on the navbar. -->
<!-- end of container-->
</div>
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
GOAL: I had to pass the php $user variable and $role to landingpage.js (in other words, make their values visible within the landingpage.js)
PROBLEM: The way I have it setup to make $user and $role variables' values visible in landingpage.js, exposes $user and $role properties when you view the page source code. I can't think of another way or setup to pass php objects $user and $role values to my external javascript file without exposing its properties.
The reason I am passing the json_encode($user) and json_encode($role) to landingpage.js is so that I can show or hide parts of the landing page depending on the role of user who is logged in.
landingpage.js
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
$(document).ready(function(){
loadDashboard();
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
Sorry for the long description. I'm fairly new with integration of PHP AJAX and JQuery and still trying to really understand how to properly setup the pages to avoid repetition of codes.
I'd appreciate any suggestion. I just thought that it's really wrong to expose the php object values during json_encode()
Thank you.

Correct way to set cookie from jQuery and read from php

I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.
When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)
I used both head tag and onload method to place the setCookie() function. But result was same.
I used this jQuery library to write cookie.
Here's code I used to read and write the cookie.
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
background: #666666;
}
</style>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript">/script>
<script>
setCookie();
function setCookie() {
console.log('on Load');
var data_spl = $(location).attr('href').split('#?camlist=')[1];
if (data_spl != undefined) {
var len = data_spl.split(',').length;
$.cookie("len", len);
console.log($.cookie("len"));
} else {
console.log('undefined');
}
}
</script>
</head>
<body>
<?php
for ($i = 0; $i < 100; $i++) {
echo "<script>console.log('START');</script>";
echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
echo $_COOKIE['len'];
echo "<script>console.log('END');</script>";
}
echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
?>
</body>
</html>
EDITED:
I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.
var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
if (retparams.has) {
console.log('sucessfuly sent the paramlen!');
} else {
alert("can't read camarauids for grid making");
}
}, 'retparams');
set_session.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
$_SESSION['urllen'] = $_POST['params'];
echo json_encode(array('retparams' => 'has'));
echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
echo json_encode(array('retparams' => 'error'));
}
?>
Then I try to read the session value ($_SESSION['urllen']) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)
As already mentioned in the comment section your Cookie isn't present on first page Load because it isn't set yet. (If you set the Cookie directly in JS or via AJAX is essentially the same)
The only way to effectively get the Information is ether with a page reload or a redirect or via AJAX request (depends on what fits your needs). For Example you could redirect in JS after the Cookie got set with:
//set your cookie in JS
window.location = location.host;
more Information about JS redirects can be found here or you search your way thru Google.
You can also set your Cookie in PHP and redirect with the header() function:
header('Location: http://www.example.com/');
More Information for PHP redirects can be found here or on Google ;)
You could check this with ajax.
Here is a simple example:
<?php
if(isset($_GET["checkIfLoggedIn"]) && boolval($_GET["checkIfLoggedIn"]) === true) {
header("Content-Type: text/json");
die(json_encode(array("isLoggedIn" => $_COOKIE["isLoggedIn"])));
exit();
} else {
var_dump($_COOKIE);
}
?>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js.cookie.js"></script>
</head>
<body>
<script type="text/javascript">
function checkIfLoggedIn() {
console.log("checking...");
jQuery.post("?checkIfLoggedIn=1", function(data) {
if(data.isLoggedIn == true) {
alert("Logged im.");
} else {
alert("NOT logged in!");
}
});
}
</script>
Set logged in to true<br/>
Set logged in to false
</body>
</html>

Executing php file from another php file

Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help

PHP SQL Query to Select Tag

I am trying to make a select have some pre-loaded options.
I have a php script that queries for these options, and I want to load them into the select on an html page.
My attempt right now..
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$("#usersList").html(data.value);
});
});
});
</script>
</head>
<body>
<form>
Find Users in: <select id="usersList" name="usersList">
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
PHP
<html>
<head>
</head>
<body>
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$ary[] =$info['State'];
}
mysql_close();
?>
</body>
</html>
My PHP works fine, but I am not sure how to get that information into my select.
All help appreciated!
First:
The html select-tag needs to get closed like this:
<select></select>
Next:
Your $ary isnt defined anywhere and it isnt returned anywhere
Use json_decode(); to return json
(and dont use any html head/body in your php file which outputs json)
Your json.php:
<?php
// Connects to your Database
mysql_connect("localhost","helloja2_Austin","mysql");
mysql_select_db("helloja2_Friends") or die(mysql_error());
$data = mysql_query("SELECT DISTINCT State FROM Clients ORDER BY State ASC")
or die(mysql_error());
$ary = Array();
while($info = mysql_fetch_array( $data ))
{
array_push($ary,$info["state"]);
}
mysql_close();
echo json_encode($ary);
?>
Next:
You need to append option tags to your select with jquery like this:
$(document).ready(function() {
$("#usersList").click(function()
{
$.getJSON('states.php', function(data) {
$.each(data,function(key,indata){
$("#usersList").append($("<option>",{
html : indata
}));
})});
});
});
Seems you have jquery library is missing. Please add it after the <head> tag and try:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the php, after mysql_close(). Add
print json_encode($ary);

Categories

Resources