how to include a jQuery file in php session file? - php

This is my php file where it creates a session for the user:-
<?php
//starting the session
session_start();
//checking if session of user is set ot not
if(isset($_SESSION['UID'])) {
echo "Welcome, ".$_SESSION['UID'];
}
else {
header("Location: ErrorPage.html");
}
?>
And this is my jQuery file:-
$(document).ready(
function hiding() {
$("#links").hide();
}
);
I want my "#links" to be hidden after a user logs in. How do I include the jQuery file in my if statement in php? I tried:-
include("jqueryFile.js");
require("jqueryFile.js");
But it didn't work.

Require and include is for server side files, like php.
you should simply do something like
echo '<script type="text/javascript" src="jqueryFile.js"></script>';
If you want to use the require/include commands you should store your javascript in a .php file
require('jqueryFile.php');

<?php if (isset($_SESSION['uid'])) { ?>
<script type="text/javascript" src="jqueryFile.js"></script>
<?php } ?>

you have to output that file (ready to deploy into client)
if (isset($_SESSION['uid'])){
?>
<script src='jqueryFile.js'></script>
<script>hiding();</script>
<?php
}

Related

jquery not working on php include file

Jquery Not Working On Include File.Here is My Code Sample.But in LocalHost That's Work Fine.and also i am using Bootstrap.
<body>
<?php
include('header.php');
if(UserType=="User")
{
// In This Portion Jquery Work :)
include('BProfile.php');
}
elseif(userType=="Premium")
{
//In this Portion Jquery Dose Not Work but file load properly :(
include('PProfile.php');
}
else
{
echo 'unable To Load Profile';
}
include('footer.php');
?>
//I also Put The Jquery On Top But Dose Not Work for PProfile
<script type="..." src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</body>
Thanks and best reagards

Session Flag doesn't work in Javascript

I use session flag in javascript for IF function. If session flag is 1, the javascript will show a specifict div on click. I have tried it manually, but the code doesn't seem to work.
This is my JS code:
$(document).ready(function(){
check = <?= $_SESSION['flag'] ?>;
$("#bag").click(function(){
if(check==0){
$("#login").show();
$("#notlogin").hide();
} else {
$("#login").hide();
$("#notlogin").show();
}
});
});
And this is the session in the head of html file:
<?php #session_start();
$_SESSION['flag']=0;
?>
Please check it in the fiddle: http://jsfiddle.net/9mm5ougu/
config-haslogin.php
<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
mysql_connect("mysql.com","name","password") or die("cannot connect");
mysql_select_db("databasename") or die("Fail here");
$myemail= $_POST['myemail'];
$mypassword= $_POST['mypassword'];
$sql= "SELECT * FROM user WHERE myemail='".$myemail."' and mypassword='".$mypassword."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
echo "Login successful";
$_SESSION['flag']=0;
header("Location:index.php");
}
?>
You can't put PHP code into a JavaScript file, because PHP is interpreted on the server side, while JavaScript is interpreted on the client side (at least here in your use case).
If you really have to do conditional treatment based on the PHP $_SESSION value, you have multiple choices (listed from the worst to the best one IMHO):
Solution 1: use a dynamic JavaScript file (the worst)
Put PHP code in your JavaScript file, but use the .php extension instead of .js. Your JavaScript code would look like something like this:
file.js.php
$("#bag").click(function(){
<?php if ($_SESSION['flag'] === 0): ?>
$("#login").show();
$("#notlogin").hide();
<?php else: ?>
$("#login").hide();
$("#notlogin").show();
<?php endif; ?>
});
And you can include this PHP file as a JavaScript file:
index.php
<script src="file.js.php"></script>
This is the worst solution:
- as you're mixing both languages, your file will soon become unreadable
- because the file is now dynamic, the user's browser can't put it on the client-side cache
- you're using PHP server's resources where it's not really necessary
- you can't deploy your file on a CDN, or on a simple server dedicated to serve static file
- you can't minify your JavaScript file
Solution 2: use two different JavaScript files
Create two different JavaScript file, one for logged in user and one for logged out. Load the correct file using the $_SESSION value.
loggedOut.js
$("#bag").click(function(){
$("#login").hide();
$("#notlogin").show();
});
loggedIn.js
$("#bag").click(function(){
$("#login").show();
$("#notlogin").hide();
});
index.php
<body>
<!-- page content here -->
<?php if ($_SESSION['flag'] === 0): ?>
<script src="loggedIn.js"></script>
<?php else: ?>
<script src="loggedOut.js"></script>
<?php endif; ?>
</body>
This solution is better than the first one because it resolves almost all points: the file is cached on the client and you don't mix PHP and JavaScript code. But this is not the best solution you can have, because it brings a lot of code duplication and it would be harder to maintain the code base.
Solution 3: bring the model client side (or sort of)
You can pass your data model to the JavaScript file, and use it directly from there. As an example, you can have a class name on the <body> tag that depends on the $_SESSION['flag'] value, and your JavaScript file will behave differently based on this value. Here is an example:
index.php
<?php
$className = $_SESSION['flag'] ? 'logged-in' : 'logged-out';
?>
<body class="<?php echo $className; ?>">
<!-- page content here -->
<script src="yourFile.js"></script>
</body>
yourFile.js
$(document).ready(function(){
var isLoggedIn = $('body').hasClass('logged-in');
$("#bag").click(function() {
if (isLoggedIn)
{
$("#login").show();
$("#notlogin").hide();
}
else
{
$("#login").hide();
$("#notlogin").show();
}
});
});
If this class is only used by the JavaScript code (it means this class will no be used in the CSS code), you should prefix it with this js- to differentiate it from real CSS class names.
While you are accessing PHP variables inside Javascript, enclose that within quotes like
check = "<?= $_SESSION['flag'] ?>";
Check this fiddle.
Use AJAX to get the data you need from the server.
For example create get-data.php:
<?php #session_start();
_SESSION['flag'] = 0;
json_encode(_SESSION['flag']);
?>
Call it from ajax:
$(document).ready(function(){ // your DOM loaded
$.ajax({
url: '/get-data.php',
success: function(response){
$("#bag").click(function(){
if(JSON.parse(response) == 0){
$("#login").show();
$("#notlogin").hide();
} else {
$("#login").hide();
$("#notlogin").show();
}
});
},
error: function(){
alert('data not loaded');
},
complete: function(){
}
})
})

Pass a PHP object for use in an external JS script

I'm grabbing some information out of a database and passing it to some JavaScript using json_encode(). The line: var row_data = <?php echo $month_stats ?>; is dumping the object into the JS.
But now I want to abstract my JS into an external file, so suddenly I can't just echo the contents of the object into the JS since PHP won't have any presence there.
So I need to somehow (via AJAX?) send the PHP object $month_stats directly to the JS so that it can use the information independently of PHP, but I'm not sure how this is implemented. Any pointers?
<?php
include 'db.php';
$month_stats = generate_monthly_count_stats($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var row_data = <?php echo $month_stats ?>;
console.log(row_data);
</script>
</head>
<body>
</body>
</html>
You can simply echo the variable and access it in an external file:
<script type="text/javascript">var row_data = <?php echo $month_stats ?>;</script>
<script type="text/javascript" src="external.js"></script>
row_data is now a global variable, so you can access it in the external.js. However it is better to add it to a namespace if you have lots of other variables..
You can create some javascripn function in .js file
myFunction(obj) {
console.log(obj);
}
in your php file you can do that:
<script type="text/javascript">
myFunction(<?php echo $month_stats ?>);
</script>
When you put the JS into an external file, make it a function with one parameter.
In your .js file:
function logRowData(var1)
{
console.log(var1);
}
In your .php file:
<head>
<?php
include(filename.js);
?>
</head>
To log the stats, you can call in the php file.
<script type="text/javascript">
logRowData($month_stats)
</script>
More info on JS Functions
If you reference the variable row_data in your included Javascript file, it should work, as you are declaring that in the global scope. Here's one article for reference: http://snook.ca/archives/javascript/global_variable

Execute PHP Session from within JS Function

I would like to set a PHP session without reloading the page when a user clicks a button. Ideally, the button click would immediately hide the div named download_div and would set the session "close_download" to true.
I understand that JS is user-side and that PHP is server-side, but I'm wondering if there is a way to blend the two worlds. Any ideas? Thanks!
<html>
<head>
<script>
function closeDownload()
{
$('.download_div').hide()
}
<?php
session_start();
$_SESSION['close_download'] = "true";
?>
</script>
</head>
<body>
Close
</body>
</html>
session.php
<?php
session_start();
$_SESSION['close_download'] = "true";
?>
download.html
<html>
<head>
<script>
function closeDownload()
{
$('.download_div').hide()
$.get("session.php")
}
</script>
</head>
<body>
Close
</body>
</html>
You have to use ajax, read the documents on jquery ajax calls, is the fastest way.
basically you have to have another php file that has this:
session_start();
$_SESSION['close_download'] = "true";
Then in your html/js you do something like $.get('newfile.php');
You can't put php in your javascript, but using ajax you can 'blend' them as u said
The way to blend the two worlds is - AJAX.
$.ajax({
url: "session.php",
data: {'name': 'test_session', 'value': 'foobar'}
}).done(function() {
$('#notification').html('Done!');
});
session.php-
<?php
session_start();
$name = $_POST['name'];
$value = $_POST['value'];
$_SESSION[$name] = $value;
?>

PHP Beginner: How to pass PHP variable from one PHP code segment to another?

I have index.php which uploads a file to server and sets several PHP variables (like $target_folder_and_file_name).
index.php also has the following line (it was originally index.html):
<script language="JavaScript" src="main.js.php"></script>
After index.php returned to the browser, the browsers asks for main.js.php from the server (right?).
Can I access somehow $target_folder_and_file_name from the PHP code in main.js.php ?
#TheJacobTaylor is right, sessions are the best, but if you dont want to keep "$target_folder_and_file_name" secret, you can also use: (index.php)
<script type="text/javascript" src="main.js.php<?php echo '?target='.urlencode($target_folder_and_file_name); ?>"></script>
and in your main.js.php
<?php
$target_folder_and_file_name = htmlspecialchars(urldecode($_GET['target']));
...
?>
with SESSIONS this would look something like this:
in your index.php
<?php
session_start();
$_SESSION['target'] = $target_folder_and_file_name;
...
echo '<script type="text/javascript" src="main.js.php"></script>';
...
?>
and in your main.js.php:
<?php
session_start();
if( isset( $_SESSION['target'] ) )
{
$target_folder_and_file_name = $_SESSION['target'];
}
else
{
$target_folder_and_file_name = FALSE;
}
...
?>
The easiest way to accomplish this is to put the information in the PHP session. Sessions last beyond one round trip. You can also add your information to a database, cache, external store, or to the URL of the javascript. As I mentioned, sessions are the easiest.
http://www.php.net/manual/en/session.examples.basic.php
<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
If you don't want everything to be session dependent, you could pass a parameter to the script when fetching it.
index.php
<?
//get filename in whatever manner you currently do
?>
<script language="JavaScript" src="main.js.php?t=<?= urlencode($filename); ?>"></script>
main.js.php
<?php
$filename = urldecode($_GET['t']);
//do whatever you need to with the filename
?>

Categories