Skip to content Skip to sidebar Skip to footer

Export Javascript When The Script Is Using Php Variables

I've got 800 lines of JS code inside a php script for a site, and littered throughout some of the JS functions are some PHP echos to insert variables from PHP. I want as much of th

Solution 1:

Add all these php-generated variables as parameters of your function:

functionvalidateCostCenter(el, local_plan_ID, cc_plants_array, std_cs_array)

BTW you could use json_encode to export your $employers array to javascript.

Solution 2:

I will illustrate possible approaches on a very simple example.

Approach 1: Computation in PHP

The page.php contains the computation and the generated Javascript file (as you have it now):

<body><?phpfunctionsum_php($a) {
    $sum = 0;
    for ($i = 0; $i < count($a); ++$i) $sum += $a[$i];
    return$sum;
}
$a = array(1, 2, 3);
$sum = sum_php($a);
?><scripttype="text/javascript">// JS generated by PHP:alert("sum_php=" + <?phpecho$sum?>);
</script></body>

Approach 2: Computation in Javascript

The computation is moved out of PHP into a separate Javascript file page.js. PHP supplies the variables to the JS functions by JSON-encoding:

(1) page.php:

<head><scripttype="text/javascript"src="page.js"></script></head><body><?php$a = array(1, 2, 3);
?><scripttype="text/javascript">
    sum_js(<?phpecho json_encode($a) ?>); // supply $a to JS function</script></body>

(2) page.js:

functionsum_js(a) {
    var s = 0;
    for (var i = 0; i < a.length; ++i) s += a[i];
    alert("sum_js=" + s);
    return s;
}

Solution 3:

Assumiong that these values are non-cacheable....

If it were me, I'd have a PHP create a global object/array to hold the values, and generate non-cacheable javascript file, then move the rest of the code into a static, cacheable file, e.g.

user_vars.php:

<?php
session_start();
....get values for variables....
print"user_vars={";
print"   '  plant': " . json_encode($plant) . "\n";
print"   ', cc_plants_array: [" . $cc_plants . "]\n";
....etc

generic.js:
functionvalidateCostCenter(el){
 var objCB = el;
 var emp_code = objCB.name.substring(23,29);
 var local_plant_ID = user_var.Plant.LocationID;
 var cc_plants_array = user_var.cc_plants_array;
.....

However unpicking what the generated values for each parameter will be can be a bit tricky - the simplest approach might be to write a temporary file as PHP generates the base HTML rather than try to create the data structures twice.

Post a Comment for "Export Javascript When The Script Is Using Php Variables"