How to write php code in js file

Is my dividing page program as a div in the first div, I added this code

<?php $table="am_users"; $query="select distinct(`user_email`) from $table"; $result=mysql_query($query); $num_rows = mysql_num_rows($result); while($data1=mysql_fetch_array($result)) { $data[]=$data1['user_email']; } sort($data); foreach($data as $search_term) { $js_data[] ="\"" . $search_term . "\""; } <script type="text/javascript"> var collection = [<?php echo implode($js_data, ","); ?>]; </script> ?> 

below this i include my css file but division 1 works in section 2, css is not applied. This problem arises because div 1 has the value of the Js variable. If I remove var collection = []; and then css is working fine. Is it possible to transfer a value from a PHP file to a JS file. Loading time

+4
source share
4 answers

Save the file as .php instead of .js and add

 Header("content-type: application/javascript"); 

. at the beginning of the file. After that, you can link to the file as

 <script type="text/javascript" src="youfile.php"></script> 
+10
source

you need to call the file with php extension

as

 <script type="text/javascript" src="/includes/slideshow.js.php"></script> 

and at the beginning of the php file

 Header("content-type: application/x-javascript"); 

See an example at http://www.givegoodweb.com/post/71/javascript-php

+4
source

Save the file with the name abc.js to abc.js.php , so the server finds out that it contains some php request, so it processes the first php content and then replaces the result in the .js file and sends it to the browser, Doing this, the .js file will contain dynamic content.

+1
source

In the question code, I see that the JS var value is set from PHP using echo. What I need to do is the other way around. These are the values ​​of the JS vars store in the var var properties. Is it possible? I can include the JS file as PHP, but I can not pass the value from JS to PHP var. PS - values ​​from JS come from an AJAX call, so I need to regularly update the values ​​in PHP var.

0
source

All Articles