How to write JSON code from PHP in JavaScript file - javascript

This is my employeeshift.js code and I can't figure out how to do a PHP code in a JavaScript file
This is my code inside the employeeshift.js but my var inorno is null
$(document).ready(function(){
var inorno= "<?php echo json_encode($inOrOut ); ?>";
if(inorno=="0"){
$('.Sales1').hide();
}else{
$('.Sales1').show();
}
});

Rename your js file to php ....or past js code to php file then do like below
<?php
//some of your main php file code ..........
?>
<script type="text//javascript">
$(document).ready(function(){
var inorno= "<?php echo json_encode($inOrOut ); ?>";
if(inorno=="0"){
$('.Sales1').hide();
}else{
$('.Sales1').show();
}
});
</script>

Your JS file is probably NOT parsed as PHP script, unless you changed some server config. One way would be to rename it to employeeshift.js.php

if this is your JS file than var value will always be null, you can assign value to a var only when the file is php and you are adding this in script tag

You can't (and probably shouldn't, even if you could) write PHP into a JavaScript file. PHP on your server doesn't "know" that it should execute any PHP code you've placed there. An alternative would be to put the JavaScript, surrounded by <script></script> tags, in a PHP file, and then your could should work.

Related

variable value to php base_url function

Below is my jQuery Code:
<script>
$(document).on('click','.quickview', function(){
var **image** = $(this).attr('image');
var testimage = document.getElementById('quickimage');
testimage.src= "<?= base_url().'assets/product_images/'.image.".png"?>";
});
</script>
I want to use this image value to the src attr of img which is in a modal, what is the best way can please help? I will be very thankful to you.
You can't use JavaScript variables in PHP, since PHP runs on the server and finishes before the page is sent to the browser.
But you don't need to use the JS variable in PHP. You can do the concatenation in JavaScript.
testimage.src= <?= json_encode(base_url()) ?> + `assets/product_images/${image}.png`;

loaded js works different to hardcoded

I have the following script that works perfect.
<script type="text/javascript">
$(document).ready(function() {
php_test();
});
</script>
<script type="text/javascript">
function php_test() {
alert('<?php echo(DIR); ?>myfile');
}
</script>
The output is as expected:
http://localhost/mvc_framework/myfile
when I put the function php_test in a file lets say ‘php_test.js’ and bind it to my footer it executes with this output:
<?php echo(DIR); ?>myfile
Any explanation? Im confused…
The way you asked the question makes it confusing. It is possible to make PHP run on all types of files on your server with a bit of Apache tweaking. My solution will make your JS files be processed by the PHP interpreter.
What you need to do is create a .htaccess file if you are using Apache. I am going to assume you are. Then you add this line into it:
AddType application/x-httpd-php .php .js
The above code will force the PHP interpreter to run on all the formats listed in the command. You can also add .htm or even .css if you need PHP to do something with those files on the server side.
Refer to this question here for a previous solution to similar question > Using .htaccess to make all .html pages to run as .php files?
Or you can just store a whole bunch of variables from the PHP end on the page as Javascript variables like this example from one of my projects:
<script type="text/javascript">
var trackFilterFlag = null;
<?php
echo "trackFilterFlag = \"". $displayedPageType ."\";\r\n";
?>
var trackFilterCategory = null;
<?php
if(strcmp($displayedPageType, "mood") === 0 || strcmp($displayedPageType, "genre") === 0) {
echo "trackFilterCategory = \"". $filterCategory ."\";\r\n";
}
?>
var sortingTracksBy = null;
<?php
if( isset($chosenSortFlag) && strlen($chosenSortFlag) > 3 && !($defaultSort) ) {
echo "sortingTracksBy = \"". $chosenSortFlag ."\";\r\n";
}
?>
</script>
Of course I was still a novice when I wrote that code, it's possible to make it much neater and just make PHP echo the whole thing, but you understand what I mean :)

How to get the php session data in javascript function of a .js file

I want to take the session data in .js file.Here i want the data in a function
Now i'm directly put the value.How to take it from session.
.js file
function callAllfnt(){
get_data(1) ;
}
I want the 1 as session data.How to take it
If you want it on page load the try this:
function callAllfnt() {
var data = "<?php echo $_SESSION['givenName']; ?>";
}
In later part in the life cycle of the application, use AJAX
1)
View File
<script type="text/javascript">
var Sessionvalue = "<?php echo $this->session->userdata('session_name')";
<script>
After load your js file
<script src="<?php echo base_url(); ?>js/file.js" type="text/javascript"></script>
JS FILE
function callAllfnt() {
var data = SessionValue;
}
(OR)
2) Using Ajax call and Get the Session value
You need to create php script that will return Session data and call that with ajax like this:
php
if (isset($_GET['var'])) {
echo json_encode($_SESSION[$_GET['var']]);
}
js with jQuery:
function get_data(variable, callback) {
$.get('session.php', {'var':variable}, function(data) {
callback(data);
}, 'json');
}
and you can call that function using:
get_data(1, function(value) {
alert(value);
});
just use php tag with in single quotes if you java script is written in html page like
function callAllfnt() {
var value = '<?php echo $_SESSION["varName"]; ?>';
get_data(value) ;
}
But if your javascript code is written seperate js file then use ajax.
Third option is if your javascript file included in php file then create a javascript variable on top of js file including code and use that variable in js file.

Calling Javascript function in an external file through php file?

Javascript code (In another file in the same directory):
function js(str)
{
alert(str);
}
PHP code(in current file):
<?php
echo '<script type="text/javascript" src="C:\xampp2\htdocs\ARD\call_jsfunc_diff_page.js"> </script>';
echo '<script>js("hello!!")</script>';
?>
I have checked on many links on the internet, i think i'm doing the right way, but the javascript function js(str) doesn't get called !!
Can somebody help me please ??
Before you edited the question: You called the function js but you are trying to call the func function.
Access to local hard disks is also problematic. Use a relative URI and access the .js over HTTP instead.

Getting PHP variable in Javascript code

I'm trying to use PHP variables in Javascript but I couldn't. After over 2000 lines of writing different JS functions I was fine avoiding that but now I really needed it. I'm a bit lost on all the ways to go about this but nothing really worked. Here is my sequence:
index.html file:
...
<script src="myfunctions.js" />
....
myfunctions.js file:
....
function test() {
var x = <?php echo $_conf['user_id'];?>
console.log(x);
}
I was trying to rename the .js file into .php file and add
header("Content-type: text/javascript");
at the beginning - that didn't work. I was trying to make .htaccess file with
AddType application/x-httpd-php .js
But that didn't work either. I'm probably missing just a tiny thing. I just need someone fresh and bright to point it out.
You can do something like this within your JS code.
var php_var = "<?php echo $_conf['user_id'];?>"
Your javascript file should be named as "javascript.php" (just put the name you want, the only important thing is the .php
You have an index.php
Write in your index.php
include("javascript.php");
Then in your javascript.php
<script>
function test(){
var variable = "<? echo $conf['user_id'] ?>";
alert(variable);
}
<script>
PS: Yo don't need any header.
Since you're doing this via a <script> tag, your PHP script MUST output valid Javascript code, as if you'd literally type your variable assignment in manually. That means doing something like:
HTML/JS:
<script src="myscript.php"></script>
PHP:
<?php
$myvar = 'foo';
?>
var myvar = <?php echo json_encode($myvar); ?>;
Which in the end, will produce somethign that will function exactly as if you'd manually typed in the following:
<script>
var myvar = 'foo';
</script>
Note the use of json_encode(). Using this ensures that whatever you're outputting from PHP will become syntactically valid Javascript.
You're not assigning PHP value to a Javascript variable. Try:
var v = "<?php echo $_conf['user_id'];?>";
index.html
..
<script src="myfunctions.js.php" />
...
myfunctions.js.php
<?php
header('Content-Type: text/javascript');
...
?>
var val = <?php echo json_encode($val); ?>;
...
Other possible solution is to assign server-side data to attributes in html and read them in javascript. For example index.html could contain something like this:
<div id="user-profile" data-user-id="<?php echo $conf['user_id']; ?>"></div>
and in js file you can get them while necessary(example with jQuery):
var userID = $('#user-profile').attr('data-user-id');
Of course you should adjust your server-side settings to process html files.

Categories