Get PHP variable value in JS file - javascript

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

Related

Access Wordpress PHP Variables within Plugin JS

edit: I'm now wondering how I can access post ID from within plugin (outside of loop). If I try to get the post id, it returns 0.
How does one access a specific page's PHP variables within a plugin JS file?
I originally had the JS in the page template file but have moved it to a plugin. Now I am unsure how to access that page's PHP variables. Maybe move the PHP logic to a plugin function?
content-course.php (JS)
<?php
$user_id = get_current_user_id();
$course_id = $post->ID;
$vimeo_progress = 0;
$vimeo_seconds = 0;
if ( is_user_logged_in() ) {
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $course_id) );
if ($row) {
$vimeo_seconds = $row->seconds_played;
$vimeo_progress = $row->progress_percent;
}
}
?>
<script>
jQuery(document).ready(function($) {
var progress = <?php echo $vimeo_progress; ?>;
var seconds = <?php echo $vimeo_seconds; ?>;
var userProgress = <?php echo $vimeo_seconds; ?>; //example user data retrieved
var lastUpdateProgress = <?php echo $vimeo_progress; ?>;
var videoUrl;
var courseID = <?php echo $course_id; ?>;
</script>
How would the JS script be able to access the PHP variables if moved to the plugin? Do I need to move the PHP above the script to a plugin function.. because then I am not sure how it would pass the data to the JS.
Wordpress have a classified function for the job
wp_localize_script()
Take a look. It's very easy to do.
http://codex.wordpress.org/Function_Reference/wp_localize_script

php in external javascript file

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>

How to use PHP variable in an external Javascript

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

from mysql to javascript variable

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.
}

php array to external page using jquery

I have a php page to creates a multi-dimentional array called $results.
I would like to:
catch submit of a form button
override default behavior of the submit using jQuery
copy and process $results on separate php using $.post
I have this which is not currently working and am not sure why?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
When selecting the xls_download_button, the alert() never fires nor does any data get passed to export_data_to_excel.php
The export_data_to_excel.php file has the following:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
I do know that the $json_results does display proper JSON encoded values when echoed. But from there are not sure why the rest of the javascript does not run; the alerts never fire nor does the JSON data get passed?
Can you see why this isn't working?
Your PHP-supplied json is not stored as a javascript variable in your js.
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
This code shouldn't run:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
It is invalid (the ; doesn't belong there). Try this code:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
Right now you are just setting a php variable called $results you need to transfear it to you javascript.
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
For sure you have an error in your javascript code (you were not closing the parenthesis after $.post), should be:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
Then you should assign your JSON to a javascript variable inside document.ready
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
You can't pass a PHP variable to the JavaScript like that: there live in totally different worlds. Use Ajax to get the JSON data from JS.

Categories

Resources