USING PHP VARIABLES IN JAVASCRIPT - Jan 22nd, 2012


I had a hard coded Javascript calculator (validate.js) that looks something like the code below, and I needed to be able
to pull the values for the calculation from a CMSB database called “Prices”.

Here’s where I started (relevant code only):

[code]
// JavaScript Document

if ($('#size1').is(':checked')) total = total + 349;
if ($('#size2').is(':checked')) total = total + 249;
if ($('#size3').is(':checked')) total = total + 299;
if ($('#size4').is(':checked')) total = total + 399;

[/code]

Here’s what worked for me:

First, I created a single record editor called Pricing” with text fields for Size2, Size2, Size3 and Size 4. (I used
descriptive text for the field labels and the size1,size2,size3 and size4 for the field names.)

After I entered in some sample prices, I changed my Javascript document validate.js to validate.js.php.
Then I put load viewer and load records code at the top of the Javascript file.
Then I added: <?php header("Content-type: text/css"); ?> to keep the code rendering happy.
Right below that I defined variables for each of the field names.

IE:
<?php $size1= $pricingRecord['size1'] ?>
<?php $size2= $pricingRecord['size2'] ?>
<?php $size3= $pricingRecord['size3'] ?>
<?php $size4= $pricingRecord['size4'] ?>

Here’s how the relevant code in my final Javascript document looked:

<?php


// load viewer library
$libraryPath = 'cmsAdmin/lib/viewer_functions.php';
$dirsToCheck = array('/your_server_path/','','../','../../','../../../');
foreach (
$dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
if (!
function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

// load records
list($pricingRecords, $pricingMetaData) = getRecords(array(
'tableName' => 'pricing',
'allowSearch' => '0',
'limit' => '1',
));
$pricingRecord = @$pricingRecords[0]; // get first record

?>
<?php
header("Content-type: text/css");
?>

<?php $size1= $pricingRecord['size1'] ?>
<?php $size2= $pricingRecord['size2'] ?>
<?php $size3= $pricingRecord['size3'] ?>
<?php $size4= $pricingRecord['size4'] ?>

// JavaScript Document

if ($('#size1').is(':checked')) total = total + <?= $size1 ?>;
if ($('#size2').is(':checked')) total = total + <?= $size2 ?>;
if ($('#size3').is(':checked')) total = total + <?= $size3 ?>;
if ($('#size4').is(':checked')) total = total + <?= $size4 ?>;



The materials on this web site have been created for use with CMS Builder content management software. CMS Builder software is published and licensed for use by InteractiveTools.com. Please contact Interactive Tools for information on the downloading of the software or the purchasing of licenses.


Terms of Service