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 the JS out of the page as possible, but I don’t know any good way to do so, as I’m not very expirenced in JS, and since I didn’t write the code I don’t even know the reason for 100% of this stuff.
Here’s an example of one of the worst offenders and one I have no idea how I’d convert out of the PHP page.
function validateCostCenter(el){
var objCB = el;
var emp_code = objCB.name.substring(23,29);
var local_plant_ID ="<?=$plant['Plant']['LocationID']?>";
var cc_plants_array = ["<?=$cc_plants?>"];
var CCPlant=false;
var CostCenterExists=false;
var std_cs_array = [];
<?
$idx = 0;
foreach($employees as $emp){
foreach($std_cs as $cs){
if($emp['Emp']['id'] == $cs[0]['emp_id']){
echo "std_cs_array[".$idx."] = [\"".trim($emp['Emp']['code'])."\",\"".$cs['0']['emp_id']."\",\"".$cs['0']['locationid']."\",\"".$cs['0']['charge_back_plant_id']."\"];\n";
$idx++;
}
}
}
?>
Would the best way to do this be to remove all the pure JS functions from the page and include them as an external file, and just leave the partly-php ones 100% as is? This is one of the most wasteful and slow pages we have on our site so I’d like it to be as optimized as possible, and separate java script files makes everything easier to debug.
Add all these php-generated variables as parameters of your function:
BTW you could use
json_encodeto export your$employersarray to javascript.