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);
Related
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
I've got an a-tag which reads as this: (and there are number of a-tags being dynamically populated as this stays inside a PHP loop.)
echo "<a onclick='trygettheid();' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
and the JS function looks like below.
function trygettheid()
{
var myvariable = $(this).attr('id');
alert(myvariable);
}
The issue is when a click is triggered, the alert says 'undefined' instead of the desired output of 'main'
Am I missing anything here?
Inside the function this does not refer to the clicked element it may be window object. To fix it pass the reference as an argument to the function. Although there is no need to use jQuery since id can be get from element id property.
PHP :
echo "<a onclick='trygettheid(this);' class='mainList' id='main' href='index.php?idd=".$reK['catid']."'><div class='AS1'>".$reK['catdescriptor']."</div></a>";
// ------^------
JS :
function trygettheid(ele){
// -----^-----
var myvariable = ele.id;
// ---^--^----
alert(myvariable);
}
I have read a half-dozen examples of how to pass parameters to javascript and they all describe the process in a very similar manner but don't speak to one event: how does the javascript code actually get called? I have seen several examples where the code is tested in $document.ready, but can't get them to work.
Here is my php code:
$base_id = 'id_'.wp_create_nonce("postlister");
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$parms = array(
'url' => $url,
'action' => $action,
'base_id' => base_id );
wp_localize_script(self::slug.'-postlister', 'postlister_parms', $parms);
And my jQuery code:
jQuery(document).ready(function (postlister_parms) {
if (postlister_parms !== undefined) {
var parms = postlister_parms;
$.diagnostic('postlister loaded');
}
});
When the page loads, there is a div generated were my code writes some additional html:
echo '<div id="'.$base_id.'"></div>';
produces:
<div id="id_c8aca14643"></div>
The footer contains:
<script type="text/javascript" src="http://localhost/mkpusa.org/nw/wp-content/plugins/rhj4-postlister/js/postlister.js?ver=3.9.2"></script>
When the jQuery code executes, postlister_parms is a function:
postlister_parms: function (a,b){return new n.fn.init(a,b)}
But postlister_parms.url, .action and .base_id are all undefined.
Please help me spot what I am missing.
The resulting code should look something like this:
var postlister_parms = {"url":"the_url","action":"the_action","base_id":"the_baseid"};
Make sure that the script with the handle self::slug.'-postlister' is enqueued before you call wp_localize_script
Have you read the Notes section of the documentation The call to wp_enqueue_script and wp_localize_script should be in a wp_enqueue_scripts action and the script should be enqueued before it is localized. That being true, it should work
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
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.