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:
function validateCostCenter(el, local_plan_ID, cc_plants_array, std_cs_array)
BTW you could use json_encode to export your $employers array to javascript.
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>
<?php
function sum_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);
?>
<script type="text/javascript">
// JS generated by PHP:
alert("sum_php=" + <?php echo $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>
<script type="text/javascript" src="page.js"> </script>
</head>
<body>
<?php
$a = array(1, 2, 3);
?>
<script type="text/javascript">
sum_js(<?php echo json_encode($a) ?>); // supply $a to JS function
</script>
</body>
(2) page.js:
function sum_js(a) {
var s = 0;
for (var i = 0; i < a.length; ++i) s += a[i];
alert("sum_js=" + s);
return s;
}
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:
function validateCostCenter(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.
Related
I saw other posts but it doesn't work. I am a bit confused here on how I implement an array into JS from PHP...
In the PHP file (test.php) I have :
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
And in JavaScript I have :
<?php include 'test.php'; ?>
...
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
So what I look for is to put $value=$row['value']; in the y : and $date=$row['date']; in the x : OR perhaps putting the entire table $table in the var data will work also .
I'm new to JavaScript, so thanks in advance..!
So in your php file....
Add a line at the bottom that converts the table to json data.
And give it a variable...
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
$jsondata = json_encode($table);
Then in your other file....
echo that variable into your data object, in the javascript.
Remember to remove that whole random number generating function...(its just an example)
Echoing PHP into javascript is definitely not considered good practice though.
And it would be better to actually do an ajax call to your php file, and insert like that....I'll also show you how to do ajax.
<?php include 'test.php'; ?>
...
data: [<?php echo $jsondata;?>], //remove that function that was here..
// it was just to generate random numbers for the demo
....
}
EDIT / UPDATE For ajax...
So for ajax...instead of assigning a variable to $jsondata.
Just return it like so...(in your PHP file)
return json_encode($table);
Then for this way....you dont include('test.php') like you did before.
Instead you just have this script inside your $(document).ready(function(){....
$.getJSON('test.php', function(myJSON) {
//and inside this function you put your highcharts stuff...
//remove that function() that generates random data
// And you will put the 'myJSON' return object inside the 'data':[] array...
// Provided you have structured your data correctly for highcharts, it should work...
// If not.... it'll be a start, and you're well on your way to debugging it
}
Hello i me and a friend have a maffia game. I have a countdown timer code but it only works when i use one timer. But i need to use it in a loop to get more timers in a table. I searched on google but nothing really helped. I saw that i had to use different id's but that didn't work for me. I have little knowledge of javascript.
This are my codes:
While loop:
while($info = mysql_fetch_object($dbres))
{
$j = 0;
$bieding = mysql_fetch_object(mysql_query("SELECT `bedrag` FROM `biedingen` WHERE `veilingid`='{$info->id}' ORDER BY `bedrag` DESC LIMIT 1"));
$tijd = ($info->tijd + $info->duur * 60 * 60 - $time);
echo '<tr>
<td>'.veilingnaam($info->id,1,1).'</td>
<td>'.usernaam($info->veiler,1,1).'</td>
<td>€'.getal($bieding->bedrag).'</td>
<td><div id="teller'.$j.'"></div></td>
</tr>';
}
Javascript part:
<script type="text/javascript">
var seconds = <?= ($tijd+1) ?>;
var countdown = document.all? document.all["teller<?= $j?>"] : document.getElementById? document.getElementById("teller<?= $j?>") : "";
var woord = "seconden";
function display()
{
seconds=seconds-1;
if(seconds==1){ woord="seconde"; }
if(seconds==0){ woord="seconden"; }
if(seconds<0)
{
self.location.replace(self.location);
}
else
{
if (countdown)
{
countdown.innerHTML=seconds+" "+woord;
setTimeout('display()',1000);
}
}
}
display();
</script>
Your while loop goes through table rows in a DB, but your JavaScript code is not part of that loop. That means you generate a HTML table for each row, but then you create <script>...</script> which includes $tijd/$j only for the last row (assuming that your while executes before the script is added to the page.
Possible workarounds:
Add a jQuery's selector, something like $("div.teller").each(function(){...}); and in that function create a timer and/or any other JavaScript code you need associated with that div.Note that this requires your div to get a CSS class "teller".
Create all JavaScript code that is needed for each DB's table row inside the PHP's while loop, but this would probably get really messy.
Also, I advise you to take a look at JavaScript's setInterval(), since it is more appropriate than setTimeout() for what you want to do.
Another thing to consider: all your timers would have a one second tick. It seems to me that it is better to have a single timer and just keep numbers of seconds (whatever that might be) in a JavaScript array (this one is easily created in PHP's while loop).
Edit: Here is one way to do this:
$data = array();
while($info = mysql_fetch_object($dbres))
{
... /* your current code */
$data[] = "{ id: 'teller$j', seconds: $tijd }";
}
$data = "[ ".implode(", ", $data)." ]";
Now, create your JavaScript code outside of the loop:
<script type="text/javascript">
var data = <?php echo $data; ?>; // It is not advisable to use <?= ... ?>
// Get references to divs via saved ids (seconds are already saved
for (i = 0; i < data.length; i++)
data.div = document.getElementById(data.id); // No need for document.all; IE supports getElementById since version 5.5
...
</script>
Now, adapt display() to work with the elements of your data array.
I have a sql query that pulls an array that contains file paths to my images.
It is store in the variable $rows and I can access individual paths by indexing throught...
IE.
$rows[0]...$rows[n]
How can I utilize java script to step through this.
Final goal is for the picture to appear with a "Next" "Previous" button under it.
Hitting next would show the next image (without a refresh)
echo $rows[0];
would print
images/a.png
Maybe using PHP's json functions you can convert your PHP array to a js array... and then use javascript functions to control which picture to show
<script type="text/javascript">
var images = <?php echo json_encode($rows) ?>, counter = 0;
function prevImage() {
counter = (counter<=0)?images.length-1:counter-1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
function nextImage() {
counter = (counter==images.length-1)?0:counter+1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
</script>
and
<img src="img/0.jpg" id="myImage" />
Previous - Next
Here is a little example to move your php array to a javascript array:
<?php
$row = array("image/image1","image/image2","image/image3");
?>
<html>
<head>
<title>Sample Array</title>
<script>
var jsArray = new Array();
<?php
for ($i=0; $i<3; $i++)
{
echo "jsArray[$i] = '$row[$i]';";
}
?>
for(i = 0; i < jsArray.length;i++)
{
alert(jsArray[i]);
}
</script>
</head>
<body>
<span>Sample Array</span>
</body>
</html>
Good luck!
Get your PHP array (server-side) to Javascript (clientside)
There are quite a few ways to go about doing this, but I'd recommend JSON. It has numerous advantages, but the most obvious one is you can store arrays and javascript objects as a string. If you're not familiar with it, this would be an excellent time to start including it in your workflow, considering you have to deal with Javascript.
PHP
Turn Array to JSON:
$jsonResults = json_encode($arrayOfResults);
Get JSON from PHP to Javascript:
<script>
var myAppsData = {};
myAppsData.slideshowJSON = JSON.parse($jsonResults);
</script>
Now your JSON object is accessible to Javascript at myAppsData.slideshowJSON.
The rest of the work is as simple as iterating through the object with a for loop (just like you would in PHP), grabbing the content and doing what you want with it.
Cheers!
so i have this problem, i'm using a index.inc.php file to set a cookie and this is a must.
The problem of setting a cookie with server-side language is that it will not take effect on the first load. The javascript is on the template file index.tpl (Using XTemplate), the COOKIE2 and COOKIE3 are values defined on the PHP, they are cookie values, but on the first load, always empty.
var ligarei = getCookie('ligarei');
if(ligarei != "nao"){
var cookie2 = {COOKIE2};
var cookie3 = {COOKIE3};
var timeout = cookie3 - cookie2;
var timeout2 = 60 - timeout;
$(document).ready(function() {
if(timeout > 60){
popthat();
}
else if(timeout < 60){
setTimeout("popthat()", timeout2 * 1000);
}
});
}
The first getCookie function is ok, it doesn't matter if it's empty or null, but the problem is on the var cookie2 and cookie3, the result after compiled is:
var cookie = ;
And this is giving me a unexpected token error .
Any hints on how to solve this?
Thanks very much.
assuming your issue is because you cant in fact change the php code to conform with a simple empty check.
var ligarei = getCookie('ligarei');
if(ligarei != "nao"){
var cookie2 = {COOKIE2} + 0; // or + "" if it is a string
var cookie3 = {COOKIE3} + 0;
var timeout = cookie3 - cookie2;
var timeout2 = 60 - timeout;
$(document).ready(function() {
if(timeout > 60){
popthat();
}
else if(timeout < 60){
setTimeout("popthat()", timeout2 * 1000);
}
});
}
Use client side JS code to read the cookie.
In your $(document).ready function, you can read the cookies from the docmuent.cookies object. There is an example here regrading how to do that:
http://www.w3schools.com/js/js_cookies.asp
Also, there are some third-party js libs that simplify this task, e.g. cookie jar:
http://cookiejar.sourceforge.net/
If you work this way, you won't need to incorporate into your code the situation in which the cookie is not set (it is actually set, but not when your server-side code is running.
Cookies are always strings. I think that you are just missing the quotes:
var cookie2 = "{COOKIE2}";
var cookie3 = "{COOKIE3}";
Whatever, you are using one language (PHP) to generate source code for another language (JavaScript) so you just be very careful to obey the syntax rules of the target language. In PHP, a usual trick is to use json_encode() to output the values. E.g.:
<?php
$value = 'Foo "bar"; test';
echo json_encode($value);
... prints a ready to use JavaScript string, quotes and all:
"Foo \"bar\"; test"
Last but not least, it doesn't really matter whether you are using a server-side language to set the cookie, as this snippet illustrates:
<?php
setcookie('current-time', date('H:i:s'));
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
window.onload = function(){
alert("Cookies: " + decodeURIComponent(document.cookie));
};
</script>
</head>
<body>
</body>
</html>
How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.