Using module params in javascript (javascript in php) - javascript

I have a simple module, and now I want to use custom module parameters in my javascript file. If I use js extension, I can not use php code, but if I try this:
$doc = JFactory::getDocument();
$doc->addScript(JURI::root() . 'modules/mod_homenewslist/js/newslist.php');
I get following error:
SyntaxError: syntax error
<script type="text/javascript">
Inside newslist.php I tried following:
<?php echo' <script type="text/javascript">' ?>
console.log(300);
<?php echo "</script>"; ?>
and:
<script type="text/javascript">
console.log(300);
</script>;
The result is the same. Is it possible to load php as script, or to use module parameters in js file?

Depending on the size of the code in your newlist.js file, you could always do it all via PHP like so:
<?php
$doc = JFactory::getDocument();
$doc->addScriptDeclaration('
alert(' . $params->get('param_name') . ');
//more js code here
');
?>
Hope this helps

Related

I am facing errors linking a variable between PHP & JS in this HTML code

I have this PHP & JS Code with me, whose task is to post a variable message to a function :
<!DOCTYPE html>
<html>
<body>
<script language="php">
$somevar = $_GET['id'];
</script>
<script>
var msg = <?php echo $somevar; ?>;
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
}
}
ThunkableWebviewerExtension.postMessage(msg);
</script>
</body>
</html>
What I want to do is, define a variable in PHP, fetch it's value in JS, and post it to the function. The reason I am using PHP is because I can get those values with PHP only. So, all I need to do is, get that PHP value into a JS variable and use it further.
When I run this code, nothing happens - but if I remove the whole PHP thing, and set the JS's var msg to a absolute string (like var msg = 'hi';) then it works. So, I think there's some problem with the linking of PHP and JS - can you please help me with this?
Any help is appreciated! Thanks!
You should not wrap PHP in <script> tags. You should wrap PHP in <?php ?>, so you need to swap this:
<script language="php">
$somevar = $_GET['id'];
</script>
with this:
<?php
$somevar = $_GET['id'];
?>
And the rest of the code seems to be OK.

Jquery if/else statement with dependencies on php session variable [duplicate]

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!
I am trying something like this:
var areaOption=document.getElementById("<?php echo #$_POST['annonsera_name']?>");
areaOption.selected=true;
Also I have tried this, but it only alerts a BLANK alert-box:
alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck
Am I thinking completely wrong here?
UPDATE
Some PHP code:
<?php
$test = "Hello World!";
?>
In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set).
Test this:
alert (<?php echo "'H'";?>);
OR
alert ('<?php echo "H";?>');
PHP runs on the server side and Javascript is running on the client side.
The process is that PHP generates the Javascript that will be executed on the client side.
You should be able to check the JS that is generated just looking at the code. Of course, if the JS relies on some PHP variables, they need to be instanciated before the JS is output.
<?php
$test = 'Hello world';
?>
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
will work but
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
<?php
$test = 'Hello world';
?>
will not
Use json_encode to convert some text (or any other datatype) to a JavaScript literal. Don't just put quotes around the echoed string — what if the string has a quote in it, or a newline, or backslash? Best case your code fails, worst case you've got a big old cross-site-scripting security hole.
So,
<?php
function js($o) {
echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
}
?>
<script type="text/javascript">
var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>);
areaOption.selected= true;
alert (<?php js('Hello World'); ?>);
</script>
Your using #$_POST indicates that you have received (or are expecting) errors - check your generated source to see if the value was output correctly. Otherwise document.getElementById will fail and you'd get no output.
alert("Delete entry <? echo $row['id']; ?> ")
If your extension is js, php will not work in that file.
The reason being, php parses on files that it is supposed to. The file types that php will parse are configured in httpd.conf using AddType commands (or directives, whatever they are called).
So you have 3 options:
add filetype js to the list of files php will parse (BAD, VERY BAD)
make the script inline to some php file
rename the file to script.js.php, and at the beginning of the file, specify the content type, like so:
<?php header( 'content-type: text/javascript' ); ?>
Cheers!

Sending a PHP session variable to javascript of another file

I extracted data from a CSV file using PHP and stored the data as a nested array.
I stored this array as a session variable and now I want to access the array in another html file using javascript. How can this be done?
<?php
session_start();
$arr=array();
$arr['1']=array('abc','def');
$arr['2']=array('123','456');
$_SESSION["abc"]=$arr;
?>
This is a sample php. I have to access the session variable in javascript.
Yes, you can use implode PHP function to convert your array to string and then echo that string and assign to a JS variable like in example below.
Your another HTML file:
<?php
session_start();
$your_array=$_SESSION['your_array'];
?>
<script>
var js_variable = [<?php echo implode($your_array,','); ?>];
console.log(js_variable);
</script>
What you should be aware of, is that php is server side and javascript is client side. So to solve this, you have 2 options:
let the php code add this variables in the head. on to of everything:
<script>
var php_variables= <?php echo json_encode($your_php_variables); ?>;
</script>
or 2. Make a seperate php file which just echos only the value in json and put a json header:
<?php
header("content-type:application/json");
echo json_encode($your_php_variables);
?>
and then let javascript retrieve it. there are many libraries available for that. but lets take a comon one like jquery:
$.get("yourphpfile.php",function(data){do something here})

How to use defined variable(defined in php file) in .js file

I have a config.php file in which I defined a variable SITE(define('SITE',"siteroot") and I have a .js file which included jquery functions. In that file, I have a variable site_root.
Is it possible I can make site_root=<?=SITE?>
I change the .js file to php file and used this code header("Content-type: application/javascript"); to defined the type of the file and include the config file. However, site_root=<?=SITE? return "".
I'm not sure if you have a typo in the question or in the actual code, but
define('SITE',"siteroot");
and
var site_root = "<?= SITE ?>";
// ^ ^ quotes matter
should work fine.
Declare PHP Variable
<?php
$variable = "abc";
?>
<script>
$("document").ready(function(){
var test = "<?php echo $variable; ?>";
alert(test);
});
</script>

How to access variable declared in PHP by jquery

For example i declare some variable like test in server side of my PHP
echo('var test = ' . json_encode($abc));
Now i want to use this test variable in Jquery ..how can i use it?
What function do i need to use it?
For Example i have:
I have back end PHP code something like this
$abc = no
echo "var test= ".json_encode($abc);
I want jquery to do the following action(client side)
$(document).ready(function(){
function(json) {
if($abc == no )//this i what i want to be achieved
}
}
I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify.
for example:
<?php
$result = array('abc' => 'no');
echo json_encode($result);
?>
This is serverside script called data.php. In Javascript you can make so:
$(document).ready(function(){
$.getJSON('data.php', function (data) {
if(data.abc === 'no') {
your code...
}
});
}
You're comparing the wrong variable:
<?php
echo <<<JS
<script type="text/javascript">
var test = {json_encode($abc)};
$(document).ready(function(){
if(test == 'no' )
// here you go
}
});
</script>
JS;
If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:
<script type="text/javascript">
var phpValue = <?php echo $abc; ?>;
alert(phpValue);
</script>
I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:
<script type="text/javascript">
var phpValue = no;
alert(phpValue);
</script>
This is very basic, but you get an idea of what you could do by using that kind of code.

Categories

Resources