Execute PHP Session from within JS Function - php

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

Related

jQuery Json response printing html tags

When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.

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

Resetting a PHP $_SESSION array with jquery function

I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions

pass query string variables without refresh page

My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.

Refreshing data in session_start()

I have two files php(index.php & data.php), the first send data to the second, and this it runs every one second and show the data.
The problem is the data is not updating
Maybe the code explains better
data.php
<?php
session_start();
$xml = simplexml_load_file("file.xml"); // the contents of the file changes every second
$json = json_encode($xml);
$_SESSION['varname'] = $json;
?>
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
session_start();
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
Thank you in advance
session_start must be called before any output (see notes in the documentation) which means you have to call session_start before any output:
<?php
session_start(); ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
You are not actually calling your data.php script from your javascript at all. Your javascript is just static at this point (look at your output source), executing the same function over and over again with the same value for newdata. You need to actually make an AJAX call to the data.php script to update the JSON.
Note that the session_start comments on this thread are important. This should be fixed as well, but that will not solve the fundamental problem you area having of wanting to use javascript to pull in the updated JSON data, but not having the value of newdata change because it is currently just static on your page.

Categories