Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the php code in js file

Tags:

javascript

php

Is my program i divide the pages 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 is working in division 2 the css is not applied . This Problem is due to the div 1 had Js variable value If I remove the var collection = []; statement then the css working fine . So Is It possible to pass the value from PHP file to JS file On Loading Time

like image 798
Meena Avatar asked Dec 08 '22 01:12

Meena


2 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 will be able to link to the file as

<script type="text/javascript" src="youfile.php"></script>
like image 136
Joyce Babu Avatar answered Dec 17 '22 06:12

Joyce Babu


what you need is to call to file with php extension

like

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

and in the beginning of php file

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

look the example in http://www.givegoodweb.com/post/71/javascript-php

like image 38
Haim Evgi Avatar answered Dec 17 '22 05:12

Haim Evgi