PHP and JavaScript Interaction: Storing Data in the Client – Part 2

In the first article in this series, we developed a simple PHP function that dynamically generates a JavaScript array and populates it with external incoming data. In this article, we will develop a real world application using this method, in the form of a news ticker.

Introduction

This is the second part of the series “PHP and JavaScript Interaction: Storing Data in the Client.” Welcome back! If you’ve been following the concepts covered in the first article, then you probably have grasped the underlying ideas behind the approach taken to store data (text files or database records) directly in JavaScript arrays, avoiding additional or unnecessary server loads.

Having thoroughly covered the pros and cons of this method, we made an attempt to develop a simple PHP function that dynamically generates a JavaScript array, populating it with external incoming data, that is, file data or table records. Once that structure was created, the question spinning in our minds was the following: can we develop a real application where this method finds its place?

The good news is that we’re able to implement several applications, at least, at a limited scale. Here, we’re not pointing toward the big project that will change your life as developer. Instead, we’re aiming to create small projects and put this approach to work, taking advantage of its benefits. So, keeping that idea in mind, in this second part, we’ll create a text file-based JavaScript news ticker, as a learning process to introduce a practical use for the technique previously defined. Are you ready to work with a pinch of PHP and JavaScript? Fine, let’s get started!

{mospagebreak title=A brief look at the “createJavaScript()” function}

Before we get our hands dirty writing some code, let’s remind ourselves how our PHP “createJavaScript()” function looked originally, in order to establish a starting point to build the JavaScript ticker. The function source code was defined as following:

function createJavaScript($dataSource,$arrayName=’rows’){

// validate variable name

if(!is_string($arrayName)){

die(‘Invalid variable name’);

}

// initialize javascript string

$javascript='<script>var ‘.$arrayName.’=[];';

// check if $dataSource is a file or a result set

if(is_file($dataSource)){

// read data from file

$row=file($dataSource);

// build javascript array

for($i=0;$i<count($row);$i++){

$javascript.=$arrayName.’['.$i.']=”‘.trim($row[$i]).'”;';

}

}

// read data from result set

else{

// check if it’s a valid result set

if(!$numRows=mysql_num_rows($dataSource)){

die(‘Invalid result set parameter’);

}

for($i=0;$i<$numRows;$i++){

// build javascript array from result set

$javascript.=$arrayName.’['.$i.']=”‘;

$tempOutput=”;

foreach($row=mysql_fetch_array($dataSource,MYSQL_ASSOC) as $column){

$tempOutput.=$column.’ ‘;

}

$javascript.=trim($tempOutput).'”;';

}

}

$javascript.='</script>’.”n”;

// return javascript code

return $javascript;

}

We’re not going to offer in-depth coverage about how the function works, because that was already done in the first part of this series. Instead, we’ll cover briefly its functionality, just to give you enough knowledge for quick implementation.

The function accepts two parameters, $dataSource and $arrayName. The first one means the source from which data are extracted, and directly fills the JavaScript array. Possible valid sources are plain text files or database result sets. The second argument determines the name of the array to be dynamically generated.

Considering these parameters, we might show an example where we’re passing an imaginary “customers.dat” text file, whose contents will populate a “customers” JavaScript array, like this:

echo createJavaScript(‘customers.dat’,’customers’);

That’s all we need. Assuming that the customers file has valid information, after executing the function, an array named “customers” will be created for us, available for processing. Simple and effective.

At this point, we’re armed with our PHP function to create arrays in the client side. Now, it’s time to build our first client application: the JavaScript news ticker. Do you think that JavaScript won’t fit your needs? You might be surprised. It’s quite powerful.

{mospagebreak title=Working in the client side: the JavaScript news ticker}

Probably a news ticker is one of the simplest and most common applications that we’ve seen on websites. Certainly, there are many ways to create such a thing, from server-side based solutions to JavaScript or Flash programs; choices are numerous.

However, the main advantage of creating this news ticker (or a similar application) is that we don’t need to work directly with JavaScript arrays to update information, since the PHP function handles the process in a transparent way for us. Any updating task is performed at a text file level, even without harming the structural HTML markup. It sounds like I’m marketing the program to you! Not really. Let’s start defining the corresponding JavaScript functions to make the news ticker work.

First, we need a file to store our news. Let’s create a simple text file, which contains the news that we need to display. The “news.txt” file would look like this:

Google expands its search capabilities adding video searching. Are you ready to submit your personal video?

PHP hits new levels of performance with PHP5. Visit www.php.net to find out more!

Want to be completely protected from Internet attacks? Disconnect your computer right now!

Interview with possible alien creature! He said they’re using MySQL to store world domination plans.

Monkey proved to be a lot smarter as a Linux system administrator in weird experiment. Oops, we’re lost!

Despite the fact that our breaking news stories are rather funny (except for the last oneā€¦just kidding!), the file is extremely simplistic. So, the next step consists of generating the JavaScript array and storing in it the file contents. How do we do it? Here, we invoke our “createJavaScript()” function with the proper parameters:

echo createJavaScript(‘news.txt’,’news’);

With this single line, we’ve created the “news” JavaScript array, directly storing the contents of the “news.txt” file into it. 

Having populated the array with our funny news, it’s time to look at the necessary JavaScript functions. If you’re not very familiar with the DOM (Document Object Model) and its methods, don’t worry. The functions are pretty easy to grasp. Trust me.

{mospagebreak title=Defining the JavaScript functions}

First, we’ll define the function “createNewsDiv()”, which will simply create the containing <div> element for displaying news in sequence. Its definition is as follows:

createNewsDiv=function(){

// create news containing <div> element

var newsDiv=document.createElement(‘div’);

newsDiv.id=’news';

// insert news <div> into document structure

document.body.appendChild(newsDiv);

}

As you can see, the above function is easy to understand. It simply creates a <div> element, then assigns to it an ID attribute “news”, handy for tying a style to the element. Finally, the function inserts it into the Web document tree. Notice that I’ve opted to append the news <div> as a new child element of the body, using the line:

document.body.appendChild(newsDiv);

However, this might be quickly changed to set a different insertion point. Let’s suppose we want to hang the news <div> element inside another container <div>. If we do so, the above expression would be replaced with the following line:

document.getElementById(‘container’).appendChild(newsDiv);

That’s not rocket science, right? Now that we’ve created the news container, let’s have a look at the next function, “rotateNews()”, which as its name implies, displays in sequence our headlines at a specified time interval. Here’s the function code:

rotateNews=function(){

// get news containing <div>

var newsDiv=document.getElementById(‘news’);

if(!newsDiv){return;}

// create new <div> element

var div=document.createElement(‘div’);

div.id=’news';

// create paragraph for each news line

var p=document.createElement(‘p’);

// style <p> element

p.style.fontFamily=’Verdana';

p.style.fontSize=’11px';

p.style.fontWeight=’bold';

p.style.color=’#c00′;

if(counter==numNews){counter=0;}

p.appendChild(document.createTextNode(news[counter]));

// insert paragraph into <div> news

div.appendChild(p);

// replace old <div> node with new <div> node

newsDiv.parentNode.replaceChild(div,newsDiv);

counter++;

// rotate news every 10 seconds

setTimeout(‘rotateNews()’,10*1000);

}

Although the function has plenty of explanatory comments, let’s break it down to see how it works. As usual, most of JavaScript tickers are governed by a counter, which controls the sequence for displaying information. In our case, we stick to that trusted technique, using the “counter” variable to program that sequence, and display the headlines at given time intervals. Bored? Just keep reading.

Our next step is to manipulate the document structure and generate the HTML elements that hold each headline. Thus, first we grasp the news <div> containing element for further replacement. Second, we create a <div> element in memory, and assign to it an ID attribute. This element will be the generic container for our news ticker, as we’ll see in a moment. Next, we need to create an HTML element to place every headline in the document.

For this purpose, I’ve decided to create a paragraph and apply a style it, specifying a font type, font size, and color, respectively. Therefore each one of the headlines will be rendered inside a <p> element. Still with me, right? Okay, now let’s check out the function’s workhorse.

Remember that we used the “createJavaScript()” PHP function to store data in the “news” array? With such a useful structure, all that we need to do is create a text node and insert the corresponding headline value into the paragraph element. The line below does exactly that:

p.appendChild(document.createTextNode(news[counter]));

As you can see, the “counter” variable behaves as a headlines pointer, to display the information in the correct sequence. Once our headline is inserted into the Web page, what else can we do? Not much, really. The only thing left is to display the headline content, increment the counter, and make the whole process happen each N milliseconds, in the following way:

// insert paragraph into <div> news

div.appendChild(p);

// replace old <div> node with new <div> node

newsDiv.parentNode.replaceChild(div,newsDiv);

counter++;

// rotate news every 10 seconds

setTimeout(‘rotateNews()’,10*1000);

I thought that we’ll never get to this point! If the explanation was a little confusing, things are going to be a lot clearer, when you see the full source code. But didn’t I forget something? Of course, the final step is to trigger both JavaScript functions, once the page is loaded:

// execute functions when page is loaded

window.onload=function(){

if(document.getElementById){

createNewsDiv();

rotateNews();

}

}

{mospagebreak title=A practical approximation: showing the news ticker in action}

Wouldn’t be convenient to put all the pieces together and illustrate how the news ticker does its job? I totally agree. In a step-by-step sequence, here’s our functional example: 

First, let’s create the “news.txt” file with some possible values:

Google expands its search capabilities adding video searching. Are you ready to submit your personal video?

PHP hits new levels of performance with PHP5. Visit www.php.net to find out more!

Want to be completely protected from Internet attacks? Disconnect your computer right now!

Interview with possible alien creature! He said they’re using MySQL to store world domination plans.

Monkey proved to be a lot smarter as a Linux system administrator in weird experiment. Oops, we’re lost!

Next, let’s work with the code:

<?php

// include the PHP function

require_once(‘createjavascript.php’);

// generate the “news” JavaScript array, populating it with news data file

// here is where the PHP-JavaScript interaction takes place

echo createJavaScript(‘news.txt’,’news’);

// display a regular HTML page including the JavaScript functions to generate the news ticker

?>

<html>

<head>

<title>CLIENT-SIDE NEWS TICKER</title>

<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />

<script language=”javascript”>

var numNews,counter;

// count number of news

numNews=news.length;

// initialize news counter

counter=0;

createNewsDiv=function(){

// create news containing <div> element

var newsDiv=document.createElement(‘div’);

newsDiv.id=’news';

// insert news <div> into document structure

document.body.appendChild(newsDiv);

}

rotateNews=function(){

// get news containing <div>

var newsDiv=document.getElementById(‘news’);

if(!newsDiv){return;}

// create new <div> element

var div=document.createElement(‘div’);

div.id=’news';

// create paragraph for each news line

var p=document.createElement(‘p’);

// style <p> element

p.style.fontFamily=’Verdana';

p.style.fontSize=’11px';

p.style.fontWeight=’bold';

p.style.color=’#c00′;

if(counter==numNews){counter=0;}

p.appendChild(document.createTextNode(news[counter]));

// insert paragraph into <div> news

div.appendChild(p);

// replace old <div> node with new <div> node

newsDiv.parentNode.replaceChild(div,newsDiv);

counter++;

// rotate news every 10 seconds

setTimeout(‘rotateNews()’,10*1000);

}

// execute functions when page is loaded

window.onload=function(){

if(document.getElementById){

createNewsDiv();

rotateNews();

}

}

</script>

<style type=”text/css”>

/*define style for news container*/

#news {

background: #eee;

padding: 2px 0px 2px 10px;

border: 1px solid #000;

}

</style>

</head>

<body>

</body>

</html>

That’s all we need. Our news JavaScript ticker is running smoothly! Of course the above list is a rough presentation. We might move the JavaScript functions out to an external file, as well as our brief CSS rules. What’s more, the complete Web page can be generated by using a template file, which rapidly separates content from logic and visual presentation. What else can we ask for?

Bottom line

In this second part, we’ve demonstrated how to use PHP-JavaScript interaction for building a nice extensible news ticker, hopefully showing that this kind of process is relatively easy to manipulate for specific purposes. But the best part is still coming! In the last part of this series, we’ll move one step beyond using this approach by building a complete record paging system, all without getting our head into the server. To find out more, stay tuned!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort