HomePHP Page 2 - PHP and JavaScript Interaction: Storing Data in the Client - Part 2
A brief look at the "createJavaScript()" function - PHP
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.
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'){
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:
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.