How do I access session variable from php in external javascript - javascript

I know this has been asked before but there's no explanation from start to finish. I have a login.php from which I want to get $_SESSION['user_id']
from
<?php
include "connect.php";
session_start();
$email=$_POST['email'];
$password=$_POST['password'];
$select_data=mysql_query("select * from user where email='$email' and password='$password'");
if(isset($_POST['email']))
{
if($row=mysql_fetch_array($select_data))
{
$_SESSION['user_id']=$row['id']; //The variable want to access from ext.js
echo "success";
}
else
{
echo "fail";
}
exit();
}
?>
By the way, this authenication works fine
My Main.php
<!DOCTYPE html>
<?php include 'connect.php';
session_start();
echo $_SESSION['user_id']; //works fine
//;
?>
<body>
//contents
<script src="login.js"></script>
<script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']
</body>
I want this variable to insert later on in a database. Any suggestions?

If you want to call php variable in external js file then you have to store value in input.
Main.php
<body>
<input type="hidden" value="$SESSION_['user_id']" class="user_id">
<script src="login.js"></script>
<script src="postad.js"></script> //the script from which I want to get $SESSION_['user_id']
</body>
postad.js
$(function(){
var user_id = $('.user_id').val();
alert(user_id);
});
And if you want to use in same file then you can directly use php echo.
Main.php
<body>
//content..
<script>
var user_id = "<?php echo $SESSION_['user_id'] ?>";
</script>
<script src="login.js"></script>
<script src="postad.js"></script> // console.log(user_id); that file you'll get that id.
</body>

You can assign session id value to a JavaScript variable to make it available for JavaScript:
<!DOCTYPE html>
<?php include 'connect.php';
session_start();
echo $_SESSION['user_id']; //works fine
//;
?>
<body>
//contents
<script>
var sessionId = "<?php echo $_SESSION['user_id'] ?>";
</script>
<script src="login.js"></script>
<script src="postad.js"></script> // "sessionId" variable should be available for the script
</body>

Related

Cannot update html text from script in php echo

I have some code like this:
<?php
echo "<script> alert('hello world!!!'); </script>";
echo "<script> document.getElementById('updatetext').innerHTML='heyatest'; </script>";
?>
<html>
<head>
</head>
<body>
<p id="updatetext">Some Text Here</p>
</body>
</html>
I need it to work this way and update the text at certain point through PHP code. In above the alert popup shows, but my text does not get updated with "heyatest"
You're calling the javascript that tries to find your id updatetext before that object exists. It cannot find it. Call the php after the html object you're looking for.
<html>
<head>
</head>
<body>
<p id="updatetext">Some Text Here</p>
</body>
</html>
<?php
echo "<script> alert('hello world!!!'); </script>";
echo "<script> document.getElementById('updatetext').innerHTML='heyatest'; </script>";
?>
The Javascript isn't calling an initiated object. Try it like this:
<html>
<head>
</head>
<body>
<p id="updatetext">Some Text Here</p>
<?php
echo "<script> alert('hello world!!!'); </script>";
echo "<script> document.getElementById('updatetext').innerHTML='heyatest'; </script>";
?>
</body>
</html>

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

Pass variable from php to javascript function argument

I want a variable that is in php to javascript function argument, but I do not get :( anyone can help me ..
//file js.js
function ComputeTotalPrice(first_meters_price){
alert(first_meters_price);//result undefined
}
<!DOCTYPE html>
<?php
...
$first_meters_price = price_type(get_geo_id("Rural"), //returns 4
?>
<script src="js.js" >
ComputeTotalPrice(<? echo $first_meters_price; ?>);
</script>
<head>
...
</head>
<body>
<div id='reserva'>
...
</div>
</body>
</html>
Try something like this:
<?php $myVar = 5; ?>
<head>...</head>
<body>
<script>
var myVarFromPHP = <?php echo $myVar; ?>;
</script>
...
</body>
Try seeing this stackoverflow answer as well
As others have mentioned and linked to external answers, content inside a script tag is unreliable and even prohibited in some browsers when a src attribute is included; as such, it should be avoided.
For this to operate properly, one approach would be to pull the function from js.js into the script tag like below. It's undesirable but it does function as needed.
<?php $first_meters_price = 4; ?>
<script type="text/javascript">
function ComputeTotalPrice(first_meters_price) {
alert(first_meters_price);
}
ComputeTotalPrice(<?php echo json_encode($first_meters_price); ?>);
</script>
like this works.. but is ot the best way to do this..
<!DOCTYPE html>
<html>
<body>
<?php $var_to_js = function_php();?>
<input type='text' class='hide' id='var_to_js' value='<?php echo $var_to_js; ?>'/>
<script>
var var_from_php = document.getElementById('var_to_js').value;
</script>
</body>
</html>

JQuery POST data to php, direct to php, data not exist anymore in php

I passed along data via POST to php using JQuery, but when the page direct to the php file, the POST["createVal"] in php doesn't seem to exit after the call back. I showed this in demo below, notice that the $name is undefined when the callback result is clicked. Any idea how to fix this?
I'm trying to make a function that when the returned result was clicked, html page could redirect to the php page in which user input in html file could be printed out.
HTML file
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<input type="text" id="userinput">
<div id="result">
</div>
</body>
<script>
$("input").keyup(function(){
var input=$("input").val();
$.post("process.php",{createVal:input},function(data){
$("#result").html("<a href='process.php'>"+data+"</a>");
})
})
</script>
</html>
php file(process.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
echo $name;
}
?>
<?php
echo $name;
?>
change
$("#result").html("<a href='process.php'>"+data+"</a>");
to
$("#result").html("<a href='process.php?createVal="+data+"'>"+data+"</a>");
and
process.php
if(isset($_REQUEST["createVal"])){
$name=$_REQUEST["createVal"];
echo $name;
}
Use this Html Code:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
</head>
<body>
<input type="text" id="userinput">
<div id="result"> </div>
</body>
<script>
$("input").keyup(function(){
var input=$("input").val();
$.ajax({
type: "POST",
url: "http://localhost/stackoverflow/process.php",
data: {'createVal': input},
success: function(data){
$("#result").html("<a href='http://localhost/stackoverflow/process.php?createVal="+data+"'>"+data+"</a>");
}
});
});
</script>
</html>
PHP Code:
<?php
if(!empty($_REQUEST['createVal']) || !empty($_GET['createVal'])){
$name = $_REQUEST['createVal'];
echo $name;
}elseif(!empty($_GET['createVal'])){
$name = $_GET['createVal'];
echo $name;
}
return 1;
?>
I have run and checked this too.
localhost: if you are running this code on localhost
stackoverflow: is the folder name, if you have any folder in localhost for it so replace the name by this.

How to pass php variable to my script code and use document.write to display it?

This is my html code.
<!DOCTYPE HTML>
<?php
$php_var = "Hello world from PHP";
?>
<html style="margin-top:-8px; margin-left:-8px;">
<head>
<meta charset="utf-8">
<title>Pure-Convert</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="calchome.css">
<script src="4func.js" type="text/javascript"></script>
<script src="converter.js" type="text/javascript"></script>
<script>
var js_var = <?php echo json_encode($php_var); ?>;
document.write(js_var);
</script>
</head>
<body >
<form action="cool.php" method="post">
<input name ="username" placeholder="Name">
<input name= "comment" placeholder="Make your mind heard..." />
<input type ="submit">
</form>
</body>
</html>
Basically what I want to happen is I want $php_var to be converted to javascript. This what I have attempted. Can someone help me accomplish this?
<script>
var js_var = <?php echo json_encode($php_var); ?>;
document.write(js_var);
</script>
Try
<script>
var js_var = "<?php echo $php_var; ?>";
document.write(js_var);
</script>
You don't need document.write(js_var);. What it does is writes that value to the DOM/HTML, possibly messing up everything (depends on the value).
<? php echo( '<script>var my_var=' . $my_value . ';</script>'); ?>
// In further js:
console.log( my_var );

Categories

Resources