Log in

View Full Version : Adding PHP to javascript



djwmguk
10-13-2009, 10:29 AM
Hey,

I have a news scroller, and I would like the content taken from a database...

Currently the content is set using a js page containing:

var pausecontent=new Array()
pausecontent[0]='<a href="http://www.javascriptkit.com">JavaScript Kit</a><br />Comprehensive JavaScript tutorials and over 400+ free scripts!'
pausecontent[1]='<a href="http://www.codingforums.com">Coding Forums</a><br />Web coding and development forums.'
pausecontent[2]='<a href="http://www.cssdrive.com" target="_new">CSS Drive</a><br />Categorized CSS gallery and examples.'

Is there a way to replace this javascript with the content from a database?

bluewalrus
10-13-2009, 02:49 PM
<?php
$increase = 0;
$increase2 = 0;
while (sqlsrv_fetch( $stmt )) {
$differentvalue[]= sqlsrv_get_field( $stmt, 0, SQLSRV_PHPTYPE_STRING( SQLSRV_ENC_CHAR));
$value[] = sqlsrv_get_field( $stmt, 1);
$anothervalue[]= sqlsrv_get_field( $stmt, 2);
$increase++;
}
echo "<script type=\"text/javascript\">\nvar ARRAY_NAME=new Array();\n";
while ( $increase2 < $increase) {
echo "ARRAY_NAME[$increase2] = $value[$increase2];\n";
$increase2++;
}
?>

I think this would do it this is for a microsoft sql server though might need some alerting if different

djr33
10-13-2009, 11:57 PM
PHP just writes text: PHP will generate html and javascript TEXT, but not be actually interactive with the javascript when it's active on the page. So you can use PHP to create database-stored content, but it will not reload once the page is active/loaded.
The above post gives a way to approach the problem, but remember that javascript and PHP do not communicate directly. You can use Ajax (a way of requesting a PHP script live through javascript) if you must have "live" php on the page.