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