How to get the values of PHP $_SESSION array in jquery? - php

I do not know if there is a better way to do this but I use this way (tell me if I am wrong) I want to make some JavaScript to show something if the user is logged in and hide that thing if the user is not logged in. but the function that did the log in credentials check is written in PHP :
function login()
{
$username = $_POST['username'];
$password = md5($_POST['password']);
$url = $_POST['url'];
$users = $GLOBALS['db']->query("SELECT * FROM users WHERE username='$username' AND password='$password'") or $GLOBALS['db']->raise_error(); // Leaving 'raise_error()' blank will create an error message with the SQL
$users_number = $GLOBALS['db']->num_rows($users);
if(!empty($users_number))
{
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['is_logged'] = 'yes';
header('Location:?'.$url);
}
}
I am trying to get and check this value of $_SESSION['is_logged'] in JavaScript but I could not is there a way to pass or to read this value from jquery or javaScript
js file:
$(".link_to_comment a").live('click',function(){
//if you are not logged in you will see a log in box (with a link to register if you are not)
if(session == 'no')
{
$("#forum").html("<form name='login_form' action='?page=functions.php&fun=login' method='post'><table><tr><td>Username:</td><td><input type='text' name='username'></td><td>error</td></tr><tr><td>Password:</td><td><input type='password' name='password'></td><td>error</td></tr><tr><td></td><td><input type='submit'></td><td>error</td></tr><tr><td></td><td><input type='hidden' name='url' value="+url+"></td><td></td></tr></table>");
}
//if you are logged in you will add your comment here
else if(session == 'yes')
{
$("#forum").find(".make_a_comment").show();
$("#forum").find(".link_to_comment").hide();
}
});
the session varibale in js file should contain $_SESSION['is_logged'] but how this is my question????

You could output the variable as a <script> within the page itself, in the global scope. This would give any external Javascript files access to the variable:
<script>
var loggedIn = <?php echo isset($_SESSION['is_logged']) && $_SESSION['is_logged'] == 'yes' ? 'true' : 'false'; ?>;
</script>
This would output var loggedIn = true; or var loggedIn = false; depending on the session variable.
Now in any other Javascript you can check the variable:
if(loggedIn == false)
{
$("#forum").html("<form name='login_form' action='?page=functions.php&fun=login' method='post'><table><tr><td>Username:</td><td><input type='text' name='username'></td><td>error</td></tr><tr><td>Password:</td><td><input type='password' name='password'></td><td>error</td></tr><tr><td></td><td><input type='submit'></td><td>error</td></tr><tr><td></td><td><input type='hidden' name='url' value="+url+"></td><td></td></tr></table>");
}
Keep in mind that you need to output the variable before any other Javascript, otherwise the variable might not exist before the other script tries to access it.

yes you can assign value to on global variable in script tag then you can use in jquery function with variable name
var isUserLoggedIn = <?php echo ($_SESSION['is_logged']) ? "true" : "false"; ?>
let me know if i can help you more.

Your js code:
session = "<?php echo $_SESSION['logged_in']; ?>";
since I have not used var so it means it is globally available in all js files.
alert(session); //will return you the value of S_SESSION

You could create dynamic Javascript code through PHP, i.e.:
var isLogged = <?php echo (isset($_SESSION['is_logged']) && $_SESSION['is_logged']) ? "true" : "false"; ?>
This way, you can dynamically create a Javascript variable isLogged that you can use in your Javascript code

Related

How to create a html button that runs a php script?

i want to create a button in html that runs a php script,
i have this script:
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest) : ?>
Log out
and i want to use it in a html button
any help?
call a js function onclick of your button and send ajax request on your script file to run php script...
<input type="button" value="Run Script" onclick="run_script();"/>
<script>
function run_()
{
$.post("yourScripFile.php",function(data){
if(data != null)
{
alert(data);
}
});
}
</script>
And in your php script file
<?php
$user = JFactory::getUser();
$userToken = JSession::getFormToken();
if (!$user->guest)
{
echo 'Log out';
die;
}
else
{
echo "else code here"; die;
}
?>
You can use a $_POST or $_GET parameter and pass it with the click of the button. Just put the script in an if block in the same page if($_GET['act'] == "logout"){//run script} and add ?act=logout to your url when you want to trigger the script. Instead of $_GET you can use $_POST and a hidden input named act

Call Javascript function from within PHP block [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
I'm working on a project for school, and I'm struggling with the login page. In my PHP code, if the user enters an incorrect username or password, I want to call a Javascript function that displays a message and briefly changes the background colour where the message is shown. Here are my JS and PHP code blocks:
<script>
var flashContent = function () {
document.getElementById("outputlogin").style.backgroundColor = "#ffff00";
document.getElementById("outputlogin").innerHTML = "Incorrect login.";
function proxy() {
updateColor(0);
}
setTimeout(proxy, 50);
}
var updateColor = function (newColor) {
var hexColor = newColor.toString(16);
if (hexColor.length < 2)
hexColor = "0" + hexColor;
var colorString = "#ffff" + hexColor;
document.getElementById("outputlogin").style.backgroundColor = colorString;
function proxy() {
updateColor(newColor);
}
if (newColor < 255) {
newColor = newColor + 5;
setTimeout(proxy, 50);
}
}
</script>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(($username == "Ben") && ($password == "thepassword")){
//echo "SUCCESS";
session_start();
$_SESSION['bensedmgallerysesh'] = session_id();
header("Location:../index.php");
}else{
if($username != "" && $password != ""){
javascript:flashContent();
}
}
?>
Right now, after hitting the login button, I get the error message:
Fatal error: Call to undefined function flashContent()
How do I fix this?
You're trying to call a client side function in a server side script. You COULD do this:
if($username != "" && $password != ""){
?>
<script type="text/javascript">
flashContent();
</script>
<?php
}
But it might be smarter to actually separate the logic in a way that prevents you from trying to write server side processing like this. Organizational skills go a long way in this business.
Have you tried doing this:
echo '<script type="text/javascript"> flashContent(); </script>';
Instead of:
javascript:flashContent();
I dont think there is such thing like javascript: functionName()..
Javascript runs in user space, interpreted by the browser.
PHP runs in server space, and is processed by a preprocessor.
What you should do there is test the username and password in PHP, and if they are wrong send back a JSON reply to the client. In the client, parse the JSON data and show the corresponding message. You may want to do this with AJAX.
Hope that works
You cannot call a Javascript function like that with php, you would need to echo out the script calling the function in javascript. Something like this might work:
<?php
echo '<script> window.onload = function(){ flashContent(); } </script>';
?>
But that might not be a great way to do it. Php runs on the server before javascript runs on the browser. One better way to have the two languages communicate is to send AJAX calls to the php script.
EDIT
To clarify: You can echo out a call to a Javascript function in the script, and it will be run where you echoed it. But here, php will still just treat Javascript as a string to be printed on the document.

Php and javascript communication : Passing javascript value to php value in the same method

I have been looking for hours, I know javascript is the client side and php is the server side and for communicating they need to use POST or whatever.
I have made this code in javascript first to retrieve the value i want and send it to php with jquery.
function getGroupName(test){
var groupName = ($(test).parent().attr('id'));
$.post("setGroup.php",{ groupName:groupName } ,function(data) {
if(data == 'yes'){
<?php
$testing = $_SESSION['currentGroup'];
$tsql2 = "select emailName,email from privacyEmails where tagID = '$tagid' and userEmail = '$testmail' and circleName = '$testing'";
$stmt2 = sqlsrv_query( $conn, $tsql2);
$order = 0;
$emailNameT = "";
$NameT = "";
while( $row = sqlsrv_fetch_array( $stmt2, SQLSRV_FETCH_NUMERIC))
{
$emailNameT = $row[0];
$NameT = $row[1];
?>
makeEditPeople('<?php echo $NameT ?>','<?php echo $emailNameT ?>','<?php echo $order ?>');
<?php
$order = $order +1;
}
?>
}
});
}
this is the php code (setGroup.php) to get the $testing :
<?php
include "connectionString.php";
session_start();
$groupName = $_POST['groupName'];
$_SESSION['currentGroup'] = $groupName;
echo "yes";
?>
Please note that the makeEditPeople() in the js is a method that append the user received in parameter into a table which works well.
My problem is : I want to send a javascript value (groupName) to SESSION value in php throught jquery $Post, then in the same time, I want to retrieve it without refreshing the page. Is that possible?
What you are looking for is called AJAX, it's a JavaScript "feature" that allows you to make requests to the server without refreshing the browser.
Since you are using jQuery it couldn't be simpler:
$.post (
'http://example.com/your.php', // URL of your script
{
Param1: 'value',
Param2: 123
},
function ( response ) {
// request holds whatever the server returned
}
);
See this for more info: http://api.jquery.com/jQuery.post/
If you are refreshing the page after you click on a link to activate and AJAX action, then this means one of two things:
You have an error in javascript (so the link ends up getting followed)
You haven't told javascript to not refresh the page.
You probably have and "onclick" or (if using jQuery "correctly") then you have $("#id").click( function(e) {} ) handler*. Make sure these "return false;" at the end
Click
function RunSomeFunction() {
// Do Stuff
return false
}
or, using jQuery
Click
$("#RunMyFunction").click( function(e) {
e.preventDefault();
// Do Stuff
return false;
)}
Notes:
You can also use other binding functions, not just click(). But click is easier to read
e.preventDefault is enough, you don't need that and return false; just giving you two options.
The issue is your "if (data == 'yes')" Javascript command cannot control whether or not inline PHP get executed; the contents there will run regardless, since it's another language all together.
The better solution is to modify setGroup.php to not return just 'yes' but both set and return the value:
<?php
include "connectionString.php";
session_start();
if (isset($_POST['groupName']))
$_SESSION['currentGroup'] = $_POST['groupName'];
echo $_SESSION['currentGroup'];
?>
Now if you POST to setGroup.php with no groupName set, it won't update the session, but will return the current value (data in the javascript function). If you do set it, it will return back the new value to Javascript.

testing a php session variable on page load with Jquery

I have a session variable that is set when the user submits a form with a certain option selected. When the page refreshes I need to test this session variable and if it exists then make some of the form read only. This is my code so far, php:
<?php
require("header.php");
if(isset($_REQUEST['searching'])){ //check if form has been submitted
echo"<h2>Submitted</H2><p>";
connect('final');//connect to DB
$fName = $_POST['addFname'];
$lName = $_POST['addLname'];
$address = $_POST['address']
$dropdown = $_POST['field']; // yes or no option
$fName = htmlspecialchars($fName);
$fName = mysql_real_escape_string($fName);
$lName = htmlspecialchars($lName);
$lName = mysql_real_escape_string($lName);
$address = htmlspecialchars($line2); // stop HTML characters
$address = mysql_real_escape_string($line2); //stop SQL injection
if($dropdown== "no"){
$_SESSION['name'] = "$fName";
}
?>
'field' is the name of my dropdown with 2 options yes and no.
MY JS for getting the variable:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type = "text/javascript">
var session;
function multi(){
$.ajaxSetup({cache: false})
$.get('getSession.php', {requested: 'foo'}, function (data) {
session = data;
});
}
</script>
I use that to get the variable from the session, getSession.php has the following:
<?php
session_start();
if (isset($_GET['name'])) {
// return requested value
print $_SESSION[$_GET['name']];
} else {
print json_encode($_SESSION);
}
?>
finally I have this function to disable the text fields
<script language="JavaScript">
<!--
function enable_text2()
{
if (session !=""){
status = "true";
document.add.addFname.readonly=readonly;
document.add.addLname.readonly=readonly;
}
}
//-->
</script>
the rest of my html is just a form, this is all in one document with the php code at the top, and the javascript functions in the head tag.
I call a wrapper function in the body onload tag, which then calls both of those functions, I thought the first function would get the session variable if it existed from the php document and then the second function would test if it was not empty, if it wasn't then it would make the fields read only.
However when I select no in the drop down and submit the form, the page refreshes and nothing happens, the fields are not read only.
Why You are using javascript for it??
session_start();
if (isset($_GET['name'])) {
$disable=true;
} else {
$disable=false;
}
<input type="text" name="addFname" <?php if($disable) { ?> readonly="readonly" <?php } ?>
Here i have taken "addFname" .you can disable any element inside that php if condition
Assuming PHP is generating the page you've got this "must be disabled" form on, there's no need for an ajax call - PHP can output a JS variable when it builds the page, e.g.
<script type="text/javascsript">
var disableForm = <?php echo (($_SESSION['somevar'] == 'whatever' ? 'true' : 'false') ?>;
if (disableForm) {
...
}
</script>

storing value in session variable, and checking it

i have made a login form on a light box using a javascript function. Now i want to store a value on session variable, so to check if the user has logined , and not to show him login lightbox again and again on his navigations on the page.. My javascript function is:
<script language="javascript" type="text/javascript">
function createlightbox()
{
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block'
}
function closelightbox()
{
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none'
}
function checksession()
{ if (admin=="admin")
{closelightbox();}
else
{createlightbox();}
}
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.name.value == "admin" && form.password.value == "admin")
{
closelightbox();
var admin = <?php $_SESSION['Admin']= 1; ?>
}
else
{
document.getElementById("error").style.display='block';/*displays error message*/
}
}
</script>
And i m calling the checksession function in my forms onsubmit event as
<form id="Admin" onreset="checksession()">
The problem is, on every reset or submit of form, even on the page changes, the login form is shown. Why it is not checking the check session function.
Please tell me any fault i m making
i'm not sure where your conditions are.
but the following code should present in php script that generates your lightbox:
<?php echo '<script> var admin ='.$_SESSION['Admin'].'</script>'; ?>
(to check above is working correctly, you could View source code of your page and see if there is a line like: <script> var admin =1</script>)
the following should be before you access admin variable setted above:
<script language="javascript" type="text/javascript">
.... //other code
function checksession()
{ if(admin =="admin")
{closelightbox();}
else
{createlightbox();}
}
....
also note that if statement should compare == not assign =

Categories