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.
}
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
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
Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});
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
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