Reading php vars in js? [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a config file in PHP.
return array(
'window_width' => 1000,
'window_height' => 800
//etc
);
How can I read these vars into my javascript? Should I echo them to the page, in perhaps a data attribute and pick them up from there? Or is there a better way?

<script>
var settings = <?php echo json_encode($your_array); ?>;
alert(settings.window_width);
</script>

Echo them directly where you need them in javascript. You can echo a javascript object to reflect the data structure. Something like this should work:
var x = <?php echo '{window_width:"1000", window_height:"800"}'; ?>;

No. You should echo them to the page.
PHP runs on server, but JavaScript on client machine, browser. In PHP you should echo something like this:
<?php
echo('<script>var myvar = '.$myvar.';</script>');
?>

Related

How to access php SESSION variable in javascript [duplicate]

This question already has answers here:
Pass a return value from php to js
(1 answer)
How to access php session in javascript file?
(4 answers)
Closed 6 years ago.
I'm trying to create an image uploading website. In this, when a user logs in, I set a $_SESSION['id'] variable in php. Now, I wish to check if $_SESSION['id'] is set in my javascript file (general.js) in order to carry out certain functions. How should I go about doing it?
<?php $session_value=(isset($_SESSION['id']))?$_SESSION['id']:''; ?>
<html>
<head>
<script type="text/javascript">
var myvar='<?php echo $session_value;?>';
</script>
<script type="text/javascript" src="general.js"></script>
</head>
<body>
</body>
</html>
In above code snippet I have initialized global variable myvar with value stored into php session variable into script file before general.js file is referenced in script.It will be accessible in general.js file
A simple example please try this
<?php
session_start();
$_SESSION['id'] = 12;
?>
<script>
alert(<?php echo $_SESSION['id']; ?>);
</script>
You can even use php variable and array as variable in js like below
<?php
$id= $_SESSION['id'];
$data= array('one', 'two', 'three');
?>
<script type="text/javascript">
var idr = '<?php echo $id; ?>';
var datar = <?php echo json_encode($data); ?>;
</script>
Here PHP is server-Side execution and JavaScript is Client side execution. and $_SESSION is a server-side construct.So probably you can not access that directly using JavaScript You would need to store that variable in $_COOKIE to be able to access it client-side.
You can get that Session using PHP, and then use that for the JavaScript like this
<?php
$variablephp = $_SESSION['category'];
?>
<script>
var variablejs = "<?php echo $variablephp; ?>" ;
alert("category = " + variablejs);
</script>
Here you are getting Session like echo $variablephp using PHP, and the assign that value to JavaScript variable.
The best way is to echo the session ID in a javascript variable.
<script>
var sessionId = "<?php echo $_SESSION['id']; ?>";
// Your javascript code goes here
</script>

send a varible through load functon [duplicate]

This question already has answers here:
Best way to pass parameters to jQuery's .load()
(2 answers)
Closed 10 months ago.
i would like to send a variable on the next page this is what i have at the moment
<? php
//some code
$ID = $_GET['ID'];
echo "<div id='show_here'></div>";
<script type ="text/javascript">
$(document).ready(function(){
setInterval(function(){
$('#show_here').load('fetch.php')
}, 3000);
});
</script>
so i would like to send the variable $ID in to the next page i assume it will be something like this .load(fetch.php?=id=$id') but it doesn't work can some one please help me out here
i think the first think is to define the variable id in the jQuery part but i do not know how to go about it please help
If I were you, I'd clean that code up properly before anything else.
<? php
//some code
$ID = $_GET['ID'];
?>
<div id='show_here'></div>
<script type ="text/javascript">
$(document).ready(function(){
setInterval(function(){
$('#show_here').load('fetch.php?id=<?php echo $ID; ?>') // we put the ID here
}, 3000);
});
</script>
In your fetch.php file, you'll need to access the $ID via $_GET again.
I'm sticking within the scope of your question here, but something to note is that you best sanitize that information. Especially if you're going to use it in a database query!
you can use
.load('fetch.php?id=<?php echo $id ?>');
or
.load('fetch.php' , {id : '<?php echo $id ?>'}) ;

Check variable in javascript with php variable [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have the php page with javascript code inside it.
If I have php variable retrieved by back-end server, can it be passed in javascript code?
For instance, if I want to check the flag(php variable) inside the javascript code, do I need to hardcode it inside the javascript?
Below are the "checkServiceCategory"? (Should it be Dynamic or static)
<?php
foreach ($result as $id=>$value) {
if($value[0]->isServiceCategory)
return true;
}
OR
isEmptyUploadFile(function(r)
{
var checkServiceCategory=document.getElementById('category-group').value;
if(checkServiceCategory!=85 && (fileList == null || fileList.length == 0))
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
location.href = "#uploadImgError";
return false;
}
else
Yes you can use php variables inside the javascript code and php variable is dynamic as
<?php $your_variable = "some value"; ?>
<script>
var js_variable = '<?php echo $your_variable; ?>';
alert(js_variable);
</script>
You can write PHP data into JavaScript before that JavaScript is loaded. So, for example:
<script>
var count = 0;
<?php
echo 'count = 5;';
?>
console.log(count); // Will give 5
</script>
You can do this because the PHP is run on the page before it is ever sent to the client. However, once the code is sent to the client, JavaScript and PHP cannot talk to each other. What you can do at that point is make AJAX requests via JavaScript from your client back to your server, and use PHP to respond to the AJAX request.
You can pass value from php to js like this.
var js_var = '<?php echo $some_php_variable; ?>';

passing variable from javascript to a php within same function [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am facing issue regarding passing javascript variables to php within same function. My code looks like this
else if(msg_type[i] == 'code' ){
var code_action = 'test';
<?php
function foobar_func(){
return "<script>document.writeln(action[i]);</script>";
}
add_shortcode( 'foobar', 'foobar_func' );
?>
}
what i am doing is passing that code_action variable of javascript and returning it to function without using ajax or jquery...is there any possible method to do so...??
any possibilities will be appreciated. Thank you
When you make a request to invoke this page, your <?PHP ?> block is executed in the server. It creates a processed output in the web page (in your code) and send it to the browser. Now the browser executes your <script> </script> blocks.
I hope you understand that passing variables from <script></script> to <?PHP ?> is impossible since the latter happened in the past.
But you can use it other way around by trying to pass variables from the PHP to JS.
When you write
<?PHP
$fromServer = "from php";
echo "<script> var fromServer = " . $fromServer . " </script>
?>
.. it passes data from your PHP to JS.
You can, however, use HTTP POST or GET method to pass data from JS to PHP to be used in the next session.

Recall a Mysql query from javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I've been trying to find out the response for this because I think it's not difficult to do, but I cannot find it.
I basically want to "recall" a mysql query that works. I have an HTML button and a span so I call a function in javascript which has a php code with the Mysql query and the result that is store in my span, works fine, but... Why I cannot click the button again to get the update results from Mysql table if I changed it ?
The syntax is something like ( in a single php file for test):
<script type="text/javascript">
function test(){
<?php include 'dbconnect.php';
$query = 'SELECT * FROM data';
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
$data = $data . "row[name]<br>";
}
mysql_close();
?>
testspan.innerHTML = <?php echo $data ?>';
}
</script>
<HTML><BODY>
<input type='button' onclick='test();'/><br>
<span id="testspan"></span
</BODY></HTML>
Resuming: when I click the first time the data appears but not the second time onwards so the Mysql query can be call just first time? anything related with the variables ?
Php is ServerSide... JS is ClientSide... you can't do code php in code JS you must use AJAX :https://api.jquery.com/jQuery.ajax/

Categories