I am trying use an array created in PHP in my external javaScript. I have PHP code that puts images from the directory depending on the userid given via url, into an array and I want to be able to use this array in javaScript so that I can create a photo slideshow and have the images change depending on the userid. I think this is achievable as I have researched online, but somehow it just doesn't work for me. I am not sure what I am doing wrong.
In the head of my html, I have this code to add in my external javaScript and to declare the variable/array in Javascript. Not sure if it's right, I got it off here from one of the solutions:
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = "<?= $galleryarray ?>";</script>
<script type="text/javascript">var userid = "<?= $user_id ?>";</script>
<script src="javascript.js"></script>
Here is my PHP code inside my basic HTML:
And here is my external JavaScript code:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
var userid = "<?php echo json_encode($user_id); ?>"; // getting php variable
var userphoto = "<?php echo json_encode(galleryarray); ?>";
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/" + userid + "/" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
PHP:
Have your PHP define the variable(s) inside of a <script> tag like this...
<script>
var userid = "<?php echo json_encode($user_id); ?>";
var userphoto = "<?php echo json_encode(galleryarray); ?>";
</script>
Your following external javascript files will then be able to use the userid and userphoto variables, even though they weren't defined directly in the external file
In the below code userphoto & userid are now javascript variables.
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = "<?= $galleryarray ?>";</script>
<script type="text/javascript">var userid = "<?= $user_id ?>";</script>
<script src="javascript.js"></script>
Php code will not be executed in external javascript file. so when below lines are executed
userid will be a string with "< ? php echo json_encode($user_id); ? > " as its value and similarly for userphoto.
var userid = "<?php echo json_encode($user_id); ?>"; // getting php variable
var userphoto = "<?php echo json_encode(galleryarray); ?>";
Modify your basic HTML to
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">var userphoto = <?php echo json_encode(galleryarray); ?>; </script>
<script type="text/javascript">var userid = <?php echo json_encode($user_id); ?>;</script>
<script src="javascript.js"></script>
and you can use these variables in external javascript file provided it is loaded after these variables are assigned. So you need not assign these variables in external javascript again.
Simply rename your file named javascript.js to javascript.php and change your script tag to <script src="javascript.php"></script>
Update
You also can use .htaccess to keep your javascript.js as it is in the script tag by doing something like the following in your .htaccess file:
RewriteRule ^javascript\.js$ javascript.php
For more details about using .htaccess in such case, checkout the
following question's answer:
Parsing PNG as PHP via htaccess works only on local server but not on webserver
Related
I have created an ACF option in the admin so a user can add cookie notice text via the admin...The javascript script I'm using creates the message within the javascript so I'm wanting to echo the ACF field within the javascript.
At the top of my cookie.js file I have: "<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>"; and I'm echoing it within a var like so: var msg = "<?php echo $cookie_msg; ?>"; so the top of my file looks like this:
"<?php $cooke_msg = the_field('cookie_notice', 'option'); ?>";
(function(){
//Change these values
var msg = "<?php echo $cookie_msg; ?>";
var closeBtnMsg = "OK";
var privacyBtnMsg = "Privacy Policy";
var privacyLink = "https://www.google.com";
//check cookies
if(document.cookie){
var cookieString = document.cookie;
var cookieList = cookieString.split(";");
// if cookie named OKCookie is found, return
for(x = 0; x < cookieList.length; x++){
if (cookieList[x].indexOf("OKCookie") != -1){return};
}
}
What I'm getting when I view the site is: <?php echo $cookie_msg; ?> and not the actual message from ACF...is there a way of actually doing this?
Wordpress giving nice function to pass PHP variable data to js file.
Put this code in your theme functions.php page.
function mytheme_load_scripts() {
wp_enqueue_script('mytheme-script', get_template_directory_uri() . '/js/mytheme-script.js');
wp_localize_script('mytheme-script', 'mytheme_script_vars', array(
'alert' => get_field("cookie_notice",$post_id)
)
);
}
add_action('wp_enqueue_scripts', 'mytheme_load_scripts');
And Create one js folder in your theme root directory. Inside that directory create the js file named mytheme-script.js file, & put the below code over there.
jQuery(document).ready(function($) {
alert( mytheme_script_vars.alert );
});
Now visit any page of your site. Surely you will get an alert with the your desire field value. Make sure you will assign proper value to $post_id. I think this will help you. Codex reference link for more details: WP Localize Script Function
I have a the code below in my js which obviously works if the js is in the php file
filter: '<?php echo $my_cat>'
how can i make a variable maybe in the php file and pull it in my external js file?
You have to place this below code at the top part of your test.php page
<script>
var filter = '<?php echo $my_cat>';
</script>
and simply you can check it on your external.js file by alert
alert(filter);
<?php
function showme(){
echo "HelloWorld";
}
?>
<script type="text/javascript">
var my_var = '<?php echo showme(); ?>' ;
</script>
You can also use short tags.
<script>
var filter = '<?=$my_cat?>';
</script>
I'm trying to find a way to get a php variable value (in admin.php file) on the javascript.js file.
This is the javascript.js file. And the from variable is the variable that should get the value from the admin.php file.
var from;
function table() {
var atttHeader1 = document.createAttribute("data-hide");
var newtHeader1 = document.createElement("th");
atttHeader1.value="phone";
newtHeader1.setAttributeNode(atttHeader1);
var colName = document.createTextNode(from);
newtHeader1.appendChild(colName);
}
This is the admin.php file. And the name variable should be passed to javascript.js.
<?php
$name = "Homer";
?>
Is there a way to include a php file inside of a js file, giving me the possibility to use global variables and call functions?
have
<script>
var from = '<?php echo $name; ?>'
</script>
I don't recommend this but
you can require the js file, and write your variable in that like var from = '<?php echo $name; ?>' in js file, and have that file like
<script>
<?php require 'asset/myfile.js' ?>
</script>
In your admin.php file
<script>
var globalSettings: {
var1: "<?=$var1;?>",
var2: "<?=$var2;?>"
}
</script>
In your javascript.js file
gloablSettings.var1; //etc
How can I access PHP variables from Javascript where the PHP code exists in a separate file?
The code I have is:
<?php
$res = "OK";
?>
<html>
<head>
<script type="text/javascript">
function myFunc()
{
res = <?php echo json_encode($res); ?>;
console.log("res = " + res);
}
</script>
</head>
<body>
<button onclick="myFunc()">Click</button>
</body>
</html>
Now, if I were to move my php code to a separate file called a.php, how can I access $res? Assume I am calling a.php with a GET request (XMLHttpRequest object).
Try-
res = "<?php echo json_encode($res); ?>";
Looking for a simple solution here, I have looked around but nothing seems to give me a simple solution. I want to get data FROM my mysql database and then into my javascript variables.
These two var items in my .js file named test.js and this file is called into my .html file.
var tag_name = 'example';
var client_id = '123456789';
In a .php file called call.php I use this method (PDO) to get the required data from MySQL:
$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name'];
$client_id = $row['client_id'];
}
I want to try and achieve something along the lines of this in the .js file test.js - this obviously wont work but hopefully sheds some light on what I am trying to achieve:
var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';
Can I do this using an Ajax method? In my research I read that I need to use JSON? If the question has been asked before, please direct me to a post that is not just someone dumping 50+ lines of code.
Here you go:
The javascript part:
$.ajax({
url: 'call.php',
dataType: 'json'
}).done(
function(data){
var tag_name = data[0];
var client_id = data[1];
}
);
The call.php file:
$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name'];
$client_id = $row['client_id'];
}
echo json_encode(array($tag_name,$client_id));
create a php script that will generate your js and instead of linking your script tag to the .js file link it to the php script that generates the js
PHP
<?php
//mysql stuff up here
header('Content-Type: text/javascript');
?>
//some js here
var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';
// some more js here
HTML
<script type="text/javascript" src="http://example.com/test.js.php"></script>
You can echo out your php variables as JSON and then consume them, but if you're just trying to set your js variables with data from php you might want to simply pass the variables in through a function call. Adding something like this to your php script to activate the Javascript you're trying to use for the page.
<script type="text/javascript">
setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>
and then creating that function in your .js file to utilize those values and do what you need.
function setVariables(name, id){
var tag_name = name
var client_id = id
//Operations that need these values.
}