How to put php content into javascript markup? - javascript

I have a video gallery, and all the titles are generated by php. The lightbox for these videos, however, is customized in javascript. How can I put the php titles inside the iframe markup?
See here:
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> <?php the_title();?> </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
EDIT
For reference, I need the attachment title below ($attachment_data['title']) in the javascript section mentioned (the markup).
<?php
$the_query = new WP_Query(array(
'post_type' => 'attachment',
'category_name' => 'video'
));
while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<?php
$attachment_data = wp_prepare_attachment_for_js( $attachment->ID );
echo'<figure><a class="video" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
echo''.the_post_thumbnail ('medium').'';
echo'<div class="photo-title"><h2>'.$attachment_data['title'].'</h2></div></a></figure>';?>
<?php
endwhile;
wp_reset_postdata();
?>

Try this:
$('.video').Lightbox({
type: 'iframe'
iframe: {
markup: '<div class="lightbox_container">'+
'<iframe class="iframe" frameborder="0" allowfullscreen></iframe>'+
'<div class="title"> <?=the_title()?> </div>'+
'</div>',
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
});
Notice the use of the <?= shorthand for echo. (read more about it)

There are a few ways to get javascript and PHP to interact. You could pull from the client using an ajax call. If you need to get a bunch of data asynchronously, that might be the thing. If you're going to have 20 copies of this iframe, you might consider using an AJAX call to pull a whole array of values/objects with JSON and then you can do with them whatever you'd like.
But... I suspect that you'll just use this iframe once per page. Rigging up some ajax for a once-per-page thing is probably a little overkill.
If you are putting your javascript right on your page, you could do as IzzEps suggested and simply echo your php values right into the iFrame. But I know most folks like to keep their javascript separate from their html content in a .js file. This makes it more maintainable. While not impossible, php most easily puts content onto .php files rather than others like js. I don't have any experience with getting a browser to use a php file for a script source.
What I've found easiest and cleanest is to write my javascript in my .js file as normal, then I'll add the variable(s) to my .php file as minimally as possible at the top in a script tag.
So, at the top of your page, you could do something like any of these:
<script>
ObjectYoureWorkingWith.Title = '<?php echo $the_title(); ?>';
var TitleObjectList = <?php echo json_encode($list_of_titles); ?>;
</script>
Basically, you feed input from your php into whatever module, object, array, or variable you're working with and then you can refer to that in your javascript wherever you need it. That way you're not forced into putting all your javascript right in with your html. You can even do this with a whole object or collection of object using json_encode (which is javascript's native object notation anyway).
Update:
I was typing the above on my cell (not the best way to respond to this sort of thing). Let me demonstrate what I'm describing:
Let's say in your php you have 20 titles you want to work with. You could make an associative array. Use an Id or whatever identifier you want to call it with.
$titleArray = [ 123 => 'Title1', 456 => 'Title2']; //(and so on....)
Then, on the php page you're wanting that data, do this:
<script>
var titleArray = <?php echo json_encode($titleArray); ?>;
</script>
This will now allow you to access it on that page (or in a js file loaded on that page) by doing this:
var myFirstTitle = titleArray["123"]; //This will return "Title1"
json_encode will take a PHP object and translate the public variables into a javascript object. Simply echoing this to a javascript variable will give javascript the object to work with.

The developer of the lightbox has a solution that I was already partly implementing. For the title to appear in the lightbox, I needed this callback from my original code:
callbacks: {
markupParse: function(template, values, item) {
values.title = item.el.attr('title');
}
But I had neglected to include the title in my PHP loop, corrected here:
echo'<figure><a class="video" title="'.$attachment_data['title'].'" href="'.get_post_meta($post->ID, 'credit_url', true).'">';
There's a similar post that also covers this answer, for reference:
Title for iframe/video in magnific popup
Thanks again for all your help!

Related

How to reuse same mixed code snippets by both PHP and JS? Best practice?

I'm just starting to learn JavaScript and PHP and am having troubles with this seemingly simple problem - how do I code reusable HTML snippets so they can be used both for JS and PHP?
Here's a case example - I have a simple .php page like this:
<body> <?php
foreach( $members_array as $member ) {
$id = $member->id;
$name = $member->name;
$img = $member->get_img();
include( 'single-member.php' );
}
foreach( $other_members_array as $member ) {
$id = $member->id;
$name = $member->name; ?>
<button type="button" onclick="addExtraMember" data-user-id="<?= $id? >">ADD <?= $name ?></button> <?php
}
</body>
Where for each member in the array a html code is dynamically generated with the variables. The 'single-member.php' is this:
<div id="<?= $id ?>">
<img src="<?= $img ?>">
<p><?= $name ?></p>
</div>
Then when the page finishes loading all the members are listed. The user of the page can click on one of the $other_members_array buttons that calls a JavaScript function. This JavaScript function should add the same code as 'single-member.php' after the last 'single-member.php' element to keep with visual consistency and in case I need to change the structure and styling of the snippet it's only in one file. I was googling this all afternoon today and here are my basic solutions:
rename the file to .html then load() and replace the attributes and text fields in JS
via .php page include one extra 'single-member.php' with empty values, a unique id and without displaying it so JS could grab it from the HTML DOM for re-use (in case the $members_array is empty)
don't load the members via PHP, add them all with JS when the page finishes loading using a reworked 'single-member.html' snippet without the PHP variables. So when a button is pressed JS function can use the 'single-member.html' again
I have a feeling this is a common problem - reusing elements and snippets between JS and PHP so I was wondering what the best practice is?
Also am I missing some more elegant library or solution?

WordPress - echo Advanced Custom Field in a .js file

I’m enqueue’ing scripts based on WordPress page template, and I need those scripts to be able to echo out ACF values. To make things more complicated, my script files dynamically build up HTML which includes custom fields e.g.:
innerHTML = '<img src="<?php echo the_field('ad_banner'); ?>"'
Is it possible to echo these fields in a .js file, to build up those HTML strings?
I've tried using wp_localize_script like below but am obviously doing something wrong:
wp_enqueue_script( 'pagination-retailers' );
wp_localize_script('pagination-retailers', 'script_vars', array(
'banner' => get_field("ad_banner")
)
);
Thanks very much
When you use wp_localize_script() its create you javascript object the name is the second argument in the function.
so you can call it in your javascript file like this
innerHTML = '<img src="'+script_vars.banner+'"';
you can also check the object in your page source code. it will be after the js file.

Get a page's source with PHP, manipulate with JavaScript

JavaScript cannot get an arbitrary page's source code, last I knew. But PHP can pretty easliy.
//get page source code with php
<?php
url = 'http://www.thesaurus.com/browse/strong?s=t';
$src = file_get_contents($url);
?>
PHP is not good at manipulating the DOM, but jQuery is great for that!
I would like to do something like
//manipulate source code with javascript
<script>
html = '"' + <?php echo $src;?> + '"';
listItems = $(html + " li");
printLists = '';
$.each(listItems, function(ind, el) {
printLists += el.innerHTML + "<br/>";
});
document.write(printLists);
</script>
But, any time I echo $src into the script tag, it gets interpreted as HTML immediately and the page becomes a live mockery of the actual site.
//Actually just shows me thesaurus.com#strong
<body>
<div id="holder" style="display: none;"></div>
<script>
holder = $("#holder");
nodeNames = [];
html = $.parseHTML(<?php echo $src;?>, holder, false);
</script>
</body>
The phrase 'virtual DOM' sounds right, though I really don't want any of the copied source code to show up at all. I just want to extract certain parts of it : to run a script from the console, search a few thesaurus sites for a term, take the results, and save them to JSON accessed by a local thesaurus script.
I have a solid idea of how to do everything else, didn't expect this to be the tricky part!
Any suggestions on preventing the browser from parsing HTML?
(I would prefer this to run just as a script file without a browser anyway, but had trouble loading jQuery in a thesaurus.js file.)
You could run a php script to get file contents and echo the results to a textarea with readonly/disabled on, then query that php file through ajax to display the resulting textarea on the page.
For example, output.php:
<?php
$str = '<p>I am a paragraph.</p>';
echo '<textarea readonly="readonly">'.$str.'</textarea>';
?>
AJAX call in the original file:
$.ajax({url: 'output.php', success: function(data) { $('#result').html(data); }});

Insert javascript string into HTML with PHP in WP

I need to create some widget for WP and in widget's setting will be textarea, where user can insert some JS code. And then my widget must inject this code to WP's footer.php with this function:
add_action( 'wp_footer', 'inject_js', 10 );
In my inject_js I have:
function inject_js () {
echo esc_attr( get_option('js_code') );
}
Everything is working good and the code inserts into HTML, but I faced one problem. In my HTML I get something like this:
<!-- BEGIN JS widget -->
<script type="text/javascript">
var __cp = {
id: "J4FGckYPdasda21OaTnqo6s7kMgeGXdTBAb6SgXMD-A"
};
As I understand I got the code from user's textarea in string type and I must do something with the quotes and other symbols, but I really don't know how to solve this issue, because I am new to PHP.
What PHP function must I use or it's possible to do with some WP functions?
I tried:
echo htmlspecialchars(esc_attr( get_option('js_code') ));
and
echo addslashes(esc_attr( get_option('js_code') ));
But nothing helped.
You are seeing the effect of esc_attr - the function is html encoding (amoungst other things) the string.
It is designed for untrusted user input. As your code is specifically designed to accept javascript from a trusted source (the site owner), dont use it.
echo get_option('js_code');
wrap your code in this :- like this:
html_entity_decode(esc_attr( get_option('js_code')));

how to insert array into javascript inside zend_form

i need to pass an array from my zend action to the view, possibly by using ajax, which is yet to be decided. in order to do that, i need to insert a script element and inside it define javascript variable, to which i will then pass my php array to, but i'm having trouble inserting script element into a zend_form. what is the easiest way to include this code into my phtml script:
<script type="text/javascript">
var obj = <?php echo json_encode($php_array); ?>;
</script>
You can use the view helper inlineScript() to pass java script to your view.
in your action $this->inlineScript()->setScript('java script here');
echo this out in your view <?php echo $this->inlineScript() ?>
you can also use the json() helper to pass json to the java script in your view.
RockyFord's solution is overly complex IMO. Just assign the PHP array to any view variable and add the code you posted (modified to use view variable) to the end of the view script - just after echoing the form.
//controller
$this->view->php_array = array(...);
//view
echo $this->form;
<script type="text/javascript">
var obj = <?php echo json_encode($this->php_array); ?>;
</script>
It will work as you expect.
Using JSON view helper is not ideal to use beacuse it modifies the headers and also disables layout by default. You can replace json_encode with Zend_Json::encode to make it work even without json_extension loaded in PHP.

Categories

Resources