Pass XML configuration file to JavaScript via cached HTML - javascript

I need to pass data from an XML configuration file to JavaScript. The application needs to work entirely offline (I'll be using application cache and localstorage) and I was planning to generate the page using PHP. Is there an easy way to place the XML in the outputted document in such a way that it will not interfere with standard HTML parsing but still be easily accessible using JavaScript.

If, as suggested by the comments, you can use json instead, then you can set it to an html tags data attribute:
<?php $settings = array('name'=>'john');?>
<div id="mydiv" data-settings="<?php echo json_encode($settings); ?>"> <!-- --> </div>
Then retrieve it in javascript:
var mydiv=document.getElementById('mydiv');
var settings=JSON.parse(mydiv.dataset.settings);
alert(settings.name); //alerts john
or simply echo it into a script tag:
<script type="javascript">
var settings=<?php echo json_encode($settings); ?>;
</script>

Related

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.

Passing variable from Php to js?

I am trying to send MY location to my js file. The location have the gives correct value when it is echoed from php. But when i try to access it from my js it does not access the correct value instead contains the value `<?php echo $location;?>` well how can i access the value in js?
PHP
while($loop->have_posts()):$loop->the_post();?>
<?php $location=get_field('location');?>
<div class="col-sm-15">
<div class="widget-box">
<div class="weather"></div>
</div>
</div>
<?php
endwhile;
locate must contain the value of location passed by php every tym the code loops` but why it is not actually passing any data?
jS file
var locate="<?php echo $location?;>";
alert (locate);
$(".weather").html(html);
The problem is you are saving the whole file in .js format where the php code you write is not parsed.
Instead you can do this just set the variable in the .php file where it can be excecuted like
PHP File
window.locate="<?php echo $location?;>";
and now use that variable in js file
alert (window.locate);
From js file one cannot access php variable.
You can do this from you php file and access locate in your js file
<script>
var locate = <?php echo $location ?>;
</script>

How to insert script tag and execute response via src?

I have a script tag which calls a remote JavaScript snippet through src, and writes it on the page, thus rendering a banner in the process.
I'm looking for a way to call the script, or insert the script via JavaScript. Right now it looks like this:
<div id="<?php print $banner_id; ?>" class="banner-responsive <?php print $breakpoints; ?>">
<script src="<?php print $url; ?>"></script>
</div>
This is the preferred method supplied by the banner vendor. I'm looking for a way to implement it more like this:
<div class="banner">
<div id="<?php print $banner_id; ?>">
<script type="text/javascript">
function banner_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = '<?php print $url; ?>';
var x = document.getElementById('<?php print $banner_id; ?>');
x.parentNode.appendChild(s);
}
if (window.attachEvent)
window.attachEvent('onload', banner_load);
else
window.addEventListener('load', banner_load, false);
</script>
</div>
</div>
This sort of works. It inserts the script tag, and calls the remote URL, but it does not execute the JS snippet received like it does in example 1, and because of that the banners do not appear. Is there a way for me to execute the script src at will?
What the src response could look like:
document.write("<a target='_blank' href='http://domain/?options'><img src='http://domain/whateever-930x180px.jpg' alt='Click here' /></a>");
I want to do this, so I can switch banners at specific moments, based on pre-defined break points. How would you go about this? Any thoughts?
Update: I don't have any control over the output. It's an external banner supplier. I take it that this is impossible?
You cannot dynamically load javascript that uses document.write() and get the result you want.
Dynamically loaded javascript runs AFTER the DOM has been loaded. When document.write() is used after the DOM has been loaded, it clears the entire document and starts a new empty document. As such, it will not do what you want.
If you want to dynamically load the Javascript, then you will need to use DOM manipulations (e.g. document.createElement() and elem.appendChild()) to insert your banner into the existing DOM and not use document.write(). document.write() is only useful for this type of problem when it is done inline with sequentially loaded javascript either inline or via <script> tags in the markup (not via dynamically loaded javascript).
There are several ways you can do this:
Instead of returning a document.write, you could return a HTML snippet and then use appendChild to write your banners. Generally using document.write is a bad javascript practice.
If you must use document.write, then rather than inserting the script tags url insert the response from the url directly into your banner_load function.

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.

How can I use a theme option in a JS file?

I'm creating a Wordpress theme and have added an option which allowed users to change a font family using (simplified code): update_option('mytheme_font', $_POST['mytheme_font']);
How do I then get the value of that option in a JS file of the theme? I need it because I'm using Cufon to replace some H1's and H2's. Thanks!
You have four options I suppose.
Output your javascript to your page inside script tags. Easiest
<script>
<?php echo 'var x = 3;' ?>
</script>
Output the variable to your page and then read that from your javascript file. Clunky, but does mean you don't have to create some js globals.
<div id="x" style="display: none;">3</div>
var x = document.getElementById('x').innerHTML();
[Added] - Use AJAX to request the data and parse after page load.
Last and I don't recommend it, but setup php to parse .js files to dynamically produce javascript files. This way you could place a <?php ?> call in your .js files.
You could echo some thing like this in the <head> of the header.php
<?php
$defaultThemeFont = "myDefaultValue";
$userThemeFont = get_option("mytheme_font");
if($defaultThemeFont == NULL)
$userThemeFont = $defaultThemeFont
?>
<script>
<?php echo "var mytheme_font = $userThemeFont;"; ?>
</script>
Now you can access this variable from any JS file

Categories

Resources