Remote JavaScripting Example - Part I

At Plymouth State we work in a multi-server environment and often wish to display dynamic content from one server in an Ajax-like fashion on another server's website. My co-worker, Zach Tirrell, and I have drummed up a solution that works to keep our layout and logic separate, while still serving our end users in a smooth, seamless, non-iFramed manner.

I'll walk through the creation of a simple search 'widget' that relies on dynamic data to populate a drop-down box.

The Tools

- PHP
- JavaScript
- XTemplate
- RemoteJSOutput: a simple script by Matthew Batchelder (me) and Zach Tirrell

Step 1: create your template

This widget is fairly simple and thus has a simple template. The template syntax is simply XTemplate syntax.

I'll name it widget.tpl and store it in a templates directory.

HTML:
  1. <!-- BEGIN: main -->
  2. <div id="sweet_borkweb_widget" style="background:#eee;border:1px solid #ccc;text-align:center;">
  3.   <div style="color:#000;">A Couple JavaScript Posts at BorkWeb</div>
  4.   <select id="borkweb_posts">
  5.     <option value=""></option>
  6.   <!-- BEGIN: post -->
  7.     <option value="{post.url}">{post.title}</option>
  8.   <!-- END: post -->
  9.   </select>
  10. </div>
  11. <!-- END: main -->

Step 2: simple template output

First we'll just spit out the template. Lets create a PHP file to do this. We'll call it widget.php

PHP:
  1. <?php
  2. include('includes/xtemplate.php');
  3. $xtpl = new XTemplate('templates/widget.tpl');
  4.  
  5. $xtpl->parse('main');
  6. $xtpl->out('main');
  7. ?>

Check out your widget so far. Its plain. Lets change that.

Step 3: add dynamic content

We want the drop down list to hold BorkWeb articles. We'll add that in now.

Note: this is where you would normally pull from a database, an RSS feed, or some other source. For simplicty, we'll be using a simple PHP array. Whoop-de-doo. Here it is:

PHP:
  1. <?php
  2. include('includes/xtemplate.php');
  3. $xtpl = new XTemplate('templates/widget.tpl');
  4.  
  5. //get list of articles
  6. $articles=array(
  7.   array('title'=>'Ajax, More Than A Buzz Word','url'=>'http://borkweb.com/story/ajax-more-than-a-buzz-word'),
  8.   array('title'=>'Ajax; Templating; and the Separation of Layout and Logic','url'=>'http://borkweb.com/story/ajax-templating-and-the-separation-of-layout-and-logic'),
  9.   array('title'=>'Deleting the Internet','url'=>'http://borkweb.com/story/deleting-the-internet'),
  10.   array('title'=>'Node Manipulation in the DOM','url'=>'http://borkweb.com/story/node-manipulation-in-the-dom'),
  11.   array('title'=>'Prototype Cheat Sheets','url'=>'http://borkweb.com/story/prototype-cheat-sheets'),
  12.   array('title'=>'Script.aculo.us Is My New Best Friend','url'=>'http://borkweb.com/story/scriptaculous-is-my-new-best-friend'),
  13.   array('title'=>'The Case For JSON: What Is It and Why Use It?','url'=>'http://borkweb.com/story/the-case-for-json-what-is-it-and-why-use-it')
  14. );
  15.  
  16. //loop over articles and place in template
  17. foreach($articles as $article)
  18. {
  19.   $xtpl->assign('post',$article);
  20.   $xtpl->parse('main.post');
  21. }//end foreach
  22.  
  23. $xtpl->parse('main');
  24. $xtpl->out('main');
  25. ?>

Check out your widget now. It has been populated with some data! w00t! Now to make it work, we return to our beloved widget.tpl template file.

Step 4: make the template work

We're going to add in some javascript. Lets make the dropdown list redirect the user to the selected article when the drop-down box changes.

I'm going to add this on our select box:

HTML:
  1. onchange="if(document.getElementById('borkweb_posts').value!='') document.location=document.getElementById('borkweb_posts').value;"

The template should now look like this:

HTML:
  1. <!-- BEGIN: main -->
  2. <div id="sweet_borkweb_widget" style="background:#eee;border:1px solid #ccc;text-align:center;">
  3.   <div style="color:#000;">A Couple JavaScript Posts at BorkWeb</div>
  4.   <select id="borkweb_posts" onchange="if(document.getElementById('borkweb_posts').value!='') document.location=document.getElementById('borkweb_posts').value;">
  5.     <option value=""></option>
  6.   <!-- BEGIN: post -->
  7.     <option value="{post.url}">{post.title}</option>
  8.   <!-- END: post -->
  9.   </select>
  10. </div>
  11. <!-- END: main -->

Step 5: prepare script for remoting

Now that our lovely widget is functioning, lets prepare it for inclusion in other locations. This is simple using RemoteJSOutput (a simple script written by Zach Tirrell and myself).

We'll include that PHP class and use it as follows:

PHP:
  1. <?php
  2. include('includes/RemoteJSOutput.class.php');
  3. $remoteOutput=new RemoteJSOutput();
  4.  
  5. //start output buffering via
  6. $remoteOutput->start();
  7.  
  8. include('includes/xtemplate.php');
  9. $xtpl = new XTemplate('templates/widget.tpl');
  10.  
  11. //get list of articles
  12. $articles=array(
  13.   array('title'=>'Ajax, More Than A Buzz Word','url'=>'http://borkweb.com/story/ajax-more-than-a-buzz-word'),
  14.   array('title'=>'Ajax; Templating; and the Separation of Layout and Logic','url'=>'http://borkweb.com/story/ajax-templating-and-the-separation-of-layout-and-logic'),
  15.   array('title'=>'Deleting the Internet','url'=>'http://borkweb.com/story/deleting-the-internet'),
  16.   array('title'=>'Node Manipulation in the DOM','url'=>'http://borkweb.com/story/node-manipulation-in-the-dom'),
  17.   array('title'=>'Prototype Cheat Sheets','url'=>'http://borkweb.com/story/prototype-cheat-sheets'),
  18.   array('title'=>'Script.aculo.us Is My New Best Friend','url'=>'http://borkweb.com/story/scriptaculous-is-my-new-best-friend'),
  19.   array('title'=>'The Case For JSON: What Is It and Why Use It?','url'=>'http://borkweb.com/story/the-case-for-json-what-is-it-and-why-use-it')
  20. );
  21.  
  22. //loop over articles and place in template
  23. foreach($articles as $article)
  24. {
  25.   $xtpl->assign('post',$article);
  26.   $xtpl->parse('main.post');
  27. }//end foreach
  28.  
  29. $xtpl->parse('main');
  30. $xtpl->out('main');
  31.  
  32. //spit out script encased in JS
  33. $remoteOutput->puke();
  34. ?>

Now check out your widget. Ugly, huh? Well, don't worry, thats the way its supposed to look for now.

Step 6: place your widget somewhere

Now that we have that beautiful chunk of code in operation, place it on a webpage somewhere.

Put this:

HTML:
  1. <script type="text/javascript" src="http://url.to/your/widget.php"></script>

on any page you wish to test your widget!

Optional Step 7: create a wrapper

If, like me, you aren't a fan of including RemoteJSOutput.class.php all over hell's half acre, you can create a wrapper. This not only allows you to minimize the code you have to repeatedly place everywhere, but it also keeps your widget.php script functional on its own!

Here's an example wrapper I'll call get_script.php which will display wrapper_widget.php (step 3's PHP file, renamed):

PHP:
  1. <?php
  2. include('includes/RemoteJSOutput.class.php');
  3. $remoteOutput=new RemoteJSOutput();
  4.  
  5. //start output buffering via
  6. $remoteOutput->start();
  7.  
  8. //create a list of allowable widgets/scripts/yadda yadda
  9. $allow=array('wrapper_widget');
  10.  
  11. //does the passed variable exist in the allowable widgets?
  12. if(in_array($_GET['script'],$allow))
  13. {
  14.   //include the wrapper
  15.   include($_GET['script'].'.php');
  16. }//end if
  17.  
  18. //spit out script encased in JS
  19. $remoteOutput->puke();
  20. ?>

So rather than using the script tag that Step 6 suggests, we'd use:

HTML:
  1. <script type="text/javascript" src="http://url.to/your/get_script.php?script=wrapper_widget"></script>

Conclusion

This method is simplistic and is simply touching on the topic of widgetization. I will be following up with dynamic user interactions in Part II, and finally discuss an open-standard widget library with xml definitions. Stay tuned :)

Download

Oh, and here's the code used in this tutorial all zipped up.

Discuss This Article


5 Responses to “Remote JavaScripting Example - Part I”

  1. AvatarGoldfarb

    I like your article.

    A lot of people criticise PHP because of its over-simplicity and downright dirty semantics. I think this shows just how awesome PHP is in the middle-tier when you compare it to more “enterprise” solutions using Java or .NET.

    Reply to this comment.
    1
  2. AvatarWandering Pig Effer

    This setup will only work if you are within the same domain - otherwise, you get permission denied errors due to cross-domain limitations. I think you need to use a JSON approach to get around this problem…

    Reply to this comment.
    2
  3. AvatarMatt
    Author Comment

    That is only if you are attempting to call the script from https. The JSON approach is fairly easy. Rather than echoing out the HTML as normal, you’d simply echo the HTML out as a string with a callback function around it (which you’d need to pass)

    Reply to this comment.
    3
  4. AvatarJames

    This is indeed a cool technique, but it’s not just limited to PHP. Java and .NET are both fully capable of generating JavaScript as well.

    For example, the JSP Servlet engine is capable of rendering JavaScript, and I would imagine that ASP is capable as well.

    The thing I like about the JSP engine is this: You can modify the deployment descriptor and tell it to process *.js files as if they were JSP files! Which means it is easier to hide the server side processing by using a *.js extension instead of *.jsp.

    Reply to this comment.
    4
  5. Avatargunabalans

    Good, i am using xtemplate , this is very useful to me in xtemplate learning perspective and any useful information pl put new article in xtemplates and php

    Reply to this comment.
    5

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Preview:

 (2805) - parse (3) - template (2) - xtemplate (2) - ajax get remote file permission denied (2) - how to start a script by remoting in a div (2) - prototype json tutorial (2) - JSON, XTemplate (2) - json prototype examples (2) - how to populate dynamic data dropdown box in jsp in java (1) - select widget php script (1) - javascript URL cheat (1) - fill dropdown json (1) - JSon script tag for https (1) - jquery .post remote domain (1) - compare script php java remote (1) - how to get when we onchange one option it will get another option using java script in php (1) - Json to dropdown (1) - xtemplate tutorial step by step (1) - ajax remote url simple example (1) - ajax get remote url (1) - javascript get json from remote location (1) - xtemplate and php tutorial (1) - server side includes xtpl document (1) - xtpl server side includes (1) - download remoting java scripting (1) - JSON javascript get data from jsp fle (1) - how to get the values from drop downbox to servlet with example (1) - allow script tag remoting (1) - jquery ajax jsp permission denied (1) - fill dropdown using jquery and php (1) - java scripting to get remote server information (1) - ajax prototype text search dropdown example (1) - XTemplate Ext js (1) - how we hide post url when post data in jsp example (1) - jQuery json permission denied (1) - JQuery with jsp Servlet example (1) - prototype get value drop down box example (1) - jsp servlet javascript sample code for dropdown box (1) - js ext examples json and java (1) - remote .js file include url (1) - script tag remoting tutorial (1) - remote walk through website dom (1) - how to include

Categories

Links