In my template view file have code below:
<script>
// When the document is ready
$(function() {
var treedata = <?php (($treedata=="" ? "":$treedata)); ?>;
$('#treeview').treeview({data: treedata});
});
</script>
but I am not using this treeview in every page, so whenever no treedata being send the output will be like this
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: treedata
Filename: views/admin.php
Line Number: 355
How can I leave it blank when no treedata being send by controller?
You could use this approach.
var treedata = <?php echo isset($treedata) ? '"'.$treedata.'"' : "''" ; ?>;
echo to display the result.
isset() to determine if variable exists
wrap the result to avoid ReferenceError: a is not defined in javascript.
You've multiple options here. My preferred stance is generally to engineer your code so that you never have undefined variables. In the absence of that code structure, you might ensure it's set:
$treedata = isset( $treedata ) ? $treedata : "";
Or, you might consider disabling the NOTICE warning altogether. How you do this is situation dependent, but you might try something like:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
Additionally, do you also have Javascript errors when $treenode is empty? I believe when $treenode is empty, your Javascript line turns into:
var treedata = ;
Which is an error. Suggest you wrap the quotes in PHP instead:
var treedata = <?php (($treedata=="" ? '""':$treedata)); ?>;
You should use isset() function for checking variable existance.
So, you should replace:
$treedata==""
To
isset($treedata)
isset() — Determine if a variable is set and is not NULL
Related
In experience.php, I have variables that are getting data from ACF, for example:
$description = get_field("desc");
What I'm looking to do is to (on click of a button), get the data from the post and open it in a modal.
Pseudo of what I'm trying to achieve:
(function($) {
$(document).on("click", '.trigger', function(e) {
console.log($description);
});
});
At the moment, I have the script in my php file which I know is incorrect (as PHP is server side and JS is client side). But, I haven't came across a way to do what I'm looking for neatly?
My approach so far (experience.php):
<?php $string = "this is a test string"; ?>
<a class="trigger">
Click me
</a>
<script>
(function($) {
$(document).on("click", '.trigger', function(e) {
console.log("<?php echo $string ?>"); // doesn't work
console.log("test"); // doesn't work
});
});
</script>
You should add quotes around PHP output, otherwise it's treated as normal JS code and will throw error about undefined variables:
console.log("<?= $string; ?>");
Your console.log("test"); does not work, because previous line throws error and halts further execution. Try switching these two lines places.
If you ever need to output object to JS variable, then there is no need for quotes:
let fooBar = <?= json_encode(["a" => 1, "b" => 2]); ?>;
// let fooBar = {"a":1,"b":2}; - visible in page source code
You need quotes around the string. Also, you need to add brackets to invoke your anonymous function.
(function($) {
$(document).on("click", '.trigger', function(e) {
console.log("<?php echo $string ?>"); // doesn't work
console.log("test"); // doesn't work
});
})(window.jQuery);
I always get this error trying to pass a variable from PHP code to javascript.
Expression expected
That's my code in Laravel 7.0 :
<script> let variable = #json($array); </script>
The code is still working. So I can use the variable $array in my javascript code. But it's always showing the error. Does anyone know how to fix this ?
You can use for example:
<script>
let variable = {!! json_encode($array) !!};
</script>`
Reference: https://laravel.com/docs/5.4/blade#displaying-data
Or if it still shows error then you can try:
<script>
let variable = [].concat(#json($array));
</script>
Hello Im trying to pass value stored in php to javascript code.
I try to pass the value in $_SESSION[user]
If I have this script in my header:
<script>
var user = ? //How to pass the value?
</script>
In my buttons I do something like this:
onclick="foo('<?php session_start(); echo $_SESSION[user];?>')
But how do I pass it without the user click?
Thanks for helping
EDIT
My JS function located in other file and I reference them by this code in my header:
<script src="class_functions"></script>
How do I pass the same parameter to the other file?
Just echo the PHP value out like you would any content:
<script>
var user = '<?php echo $_SESSION[user]; ?>';
</script>
JavaScript is just client-side code like HTML is.
If you're PHP script is rendering the page, I would go with the script tag approach.
<head>
<script type="text/javascript">
var user = '<?php echo $_SESSION["user"]; ?>';
</script>
</head>
<body>
</body>
Now that you have added an additional factor to your question, it is a little bit more interesting. If you need to set a variable when the functions that use this variable are located in a different file, then you need to decide the scope of the variable you are passing. There are several options; I will just list two:
Global scope. That is, the variable will be "known" to the other functions because of where it it located. You want to be careful of this, but if that's your approach you can use any of the answers given, e.g.
<script>
var x = '<?= $_SESSION["user"];>';
</script>
Local scope. Now you will need to include a function in class_functions that sets the variable. You might end up with something like
<script>
set_user('<?= $_SESSION["user"];>');
</script>
Where the set_user() function is defined in your other file, and ensures that the variable is available to the other functions with the correct scope.
I would prefer using method 2 - it is much cleaner.
I think this is better:
<script>
var user = '<?php echo htmlentities($_SESSION["user"]); ?>';
</script>
Because if there are quotes $_SESSION['user'], you will get an error.
For example if you have:
$_SESSION['user'] = "something with 'quotes'";
the js would like so:
var user = 'something with 'quotes'';
Which is incorrect.
You Can use Jquery ,if you want it to happen automatically.
just Use the following code inside your tags
$(document).ready(function()
{
var user= <? echo $_SESSION['user']?>;
//Code Goes here......
});
Hope that solves Your Problem
Note:This can be one of the many possible solutions
In Jade you can pass through an object to the client like this
Route:
res.render('mypage', {
title: 'My Page',
myobject : data
});
Jade Template:
extends layout
block navbar
include includes/navbar
block top
include includes/top
block content
script(src='/js/controllers/test-controller.js')
script.
var clientobj = !{JSON.stringify(myobject)}
But what if myobject does not exist? It seems like it would be the simplest thing to check if this object exists before using it (and therefore only try to define the var clientobj if it does) but I am banging my head here trying to get make this happen.
Eg:
res.render('mypage', {
title: 'My Page'
});
Will currently break the given template, there has to be some syntax to make this code more resilient, surely..
The following code snippet should help.
script
if myobject
| var clientobj = !{JSON.stringify(myobject)}
Please note that you should not put . (dot) at the end of script element. Otherwise if myobject ... will be considered as text and not Jade code.
Alternatively this should work too:
script.
var clientid = #{myobject ? JSON.stringify(myobject) : "undefined"};
In that case you will get following HTML code and you will have to handle clientid as undefined in your JavaScrip code in a page.
<script>var clientid = undefined;</script>
I hope that will help
I'm trying to troubleshoot a problem with someone else's JavaScript file, and they declared a function like the following.
function window.confirm(str) {
..... code here .....
}
This works fine with IE, but in Google Chrome, it throws an uncaught syntax error on the period in window.confirm. I tried to put a try catch around it like below, but that didn't work, same syntax error. It then won't let me use any functions defined in that JavaScript file.
try {
var window.confirm = function(str) {
..... code here .....
};
}
catch(e) {}
I also tried to change the declaration to a variable, like below, but that didn't work either. Same error.
var window.confirm = function(str) {
..... code here .....
};
Is there a way to catch this in Chrome?
function window.confirm(str) and var window.confirm ... are invalid. instead, try:
window.confirm = function(str){
..... code here .....
}
Two points :
try/catch are used to detect execution errors, not compilation ones. Don't deploy code with syntax errors.
function window.confirm(){ is a MS idiom you must avoid. You may use window.confirm = function() { or, if you're in the global scope, simply var confirm = function() {.
If you absolutely need to try and catch "Uncaught SyntaxError" errors, then you'll have to rely on JavaScript's hidden-under-the-floorboard misunderstood stepchild eval() function.
In the sample code below, obj will only be updated if the incoming string evaluates to a valid object; otherwise obj will default to {}. Let's assume $someTextField pulls in settings entered in a CMS textarea field, and the content editor has entered this malformed string in the field:
{
"foo": "bar
}
Sample code:
var oSettings = {};
// Returns "Uncaught SyntaxError: Unexpected token ILLEGAL(…)"
try {
oSettings = <?php echo $someTextField ?>;
} catch(e) {}
// This works
try {
eval('oSettings = <?php echo $someTextField ?>');
} catch(e) {}
Keep in mind that if the string to be evaluated is coming from some external source (e.g., CMS) and you have no control over it as in this example, then you'll need to do three things:
Detect and prevent execution of JavaScript code that could potentially wreck hell on your app.
Escape quotes in the incoming string to avoid conflicts with the JavaScript quotes. Since we're using PHP in this example, it would be better to do something like this:
eval('oSettings = <?php echo addslashes($someTextField) ?>');
Remove line breaks since the evaluated string needs to be on one single line. It would be even better to do something like this:
eval('oSettings = <?php echo addslashes(str_replace(array("\r\n", "\n", "\r"), "", $someTextField)) ?>');
You must fix the syntax errors. Try/catch will not catch syntax errors because syntax errors are compile time errors and try/catch can only catch runtime errors.