Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Wednesday, February 13, 2008

Passing variables between Javascript and PHP

First off, an apology for not blogging in so long; I'm in the thick of my final semester, and most of my time goes towards writing my thesis or working on my independent project (likely to be mentioned in a later post). But this material I just created for work is good enough, I think, that it's worth sharing.


Javascript and PHP, when used together, can make pretty much anything you desire in a website. You use your PHP to talk to your databases, generate dynamic content, and hold session information, while your Javascript can refine the user interface, adding options and making changes to the window on the fly.

But what if you need to get these two technologies to talk, securely? PHP is rendered server-side, before the page is produced and sent to the client. Thus, you can easily send PHP variables to a Javascript, if you don't mind their values being known to the user. However, if you need to keep your PHP variables safely server-side, how can you get Javascript to send its variables along to PHP?

Here's what I came up with: I call it "12th Hour Javascript", which will make sense shortly. The basic premise:
  1. write a PHP script that takes in a URL variable ($_GET), runs whatever safe server-side function necessary, then outputs a Javascript function that simply returns the output of the PHP function.
  2. write a Javascript function that adds an inclusion of the above file, taking in whatever variables and tacking them onto the URL of the src.
  3. Call the function in 2) in one event, and the function in 1) in an immediate, subsequent event. 2) will pass the URL parameters to 1) as it includes it in the HTML file. the function in 1) will then be available for the next event.
Sound vague? Some example code may help.

ourscript.php:
function php_js() {
<?php
function core($parameter){
// Do stuff
return $output
}
$js_return = core($_GET['URL_param']);
echo "return " . $js_return . ";";
?>
}

Our Javascript function:
function twelfth_hour() {
var html_doc = document.getElementsByTagName('head').item(0);
var js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', 'Ourscript.php?URL_param='+document.SOME_ELEMENT.parameter.value);
html_doc.appendChild(js);
return false;
}

Using the functions in an HTML form:
<input value="go" onmousedown="twelfth_hour();" onclick="php_js();" type="submit" / >


As you see, the second function (twelfth_hour) will run first, and add a new Javascript to the document, with the source equaling ourscript.php?URL_param=parameter. Ourscript.php takes that parameter, processes it as we like, and gives us the output. If a user were to look at Ourscript.php, all they'd see would be a function that returns a value; all the inner workings are in PHP and thus hidden.

Keep in mind that the calls to these functions must exist in separate events. Trying to run them together results in an undefined error for php_js(), since it hasn't been included into the document yet. Javascript functions do not execute line-by-line, and perhaps not even function by function. However, event by event, you can keep one step ahead of your Javascript, and provide it with the dynamically-generated, PHP-based scripts you need.

Minor tweaks and refinements may be necessary, given your particular application and server configuration.

Comments are welcome.

Friday, June 22, 2007

Mastering PHP's XML Parser

Probably not the most exciting subject for anyone else, but I've spent a lot of hours in the last couple days writing a script to automatically read ATOM feeds into a webpage. And yes, I'm aware that such things already exist, and can be found easily on Sourceforge, but doing it myself helped get me that much deeper into working with PHP, and made sure that I understood both the ATOM schema and PHP's XML Parser.

The XML Parser requires several functions to be put into it in order to do whatever it is you want it to do. You need a function to deal with start tags, one for end tags, and one for character data between those tags. The only place you can deal with attributes is within the start tag function. It helps, then, to have some global variables to store the information you desire to pluck out of an XML document. This sounded like something suited for an object-oriented approach, so I started by building a class called ATOMParser. I made the start, end and character functions internal, and created two public functions, one to parse a document, the other to set how many results to return and which label to search for.

Here entered a wrinkle; on my server, where I did much of my testing, I run PHP 4.something, whereas the university server has PHP 5.something. PHP 5 has a whole bunch of reserved words like public, private and interface, whereas PHP 4 does not. To make things work on both ends, I had to go generic with my terms. It all worked fine, but theoretically, someone could call the start or end functions from outside the ATOMParser object... for what little good it would do.

Another difference: on my server, I could simple open the XML straight away, whereas on the URI server it was necessary to stream the document in chunks, then open it. What does this mean? Well, using code that worked on my server to display all the different posts in the blog only showed the latest post (maybe the latest two, if I refreshed just right) on the URI server. The packeting fixed that.

So, my end result is a pretty portable piece of PHP that I can use elsewhere on the GSLIS site. You can see its current implementation at www.uri.edu/artsci/lsc. More will follow, notably the joblist. I will also likely use this somewhere in my website for bringing in blog info (same blog package as GSLIS). For other XML documents, I can now create custom parsers to do my bidding. Very exciting.

Well, to me, at least.