i want to tidy up my index.php. i have some scripts which i want to move to another files.
atm i come to this, i hava javascript which has php in it to echo values from database. i came to solution, copy that to another php file, like script.php, and just include it with php.
<!-- AUTO complete -->
<script src="/pages/JQuery/js/jquery-1.8.3.js"></script>
<script src="/pages/JQuery/js/jquery-ui-1.9.2.custom.js"></script>
<link rel="stylesheet" type="text/css" href="/pages/JQuery/css/no-theme/jquery-ui-1.10.3.custom.css" />
<?php include './pages/skripti/autocomplete.php'; //pats skripts ?>
and
<script>
jQuery(function($) {
var availableTags = [
<?php
$names = $db->query("SELECT * FROM names");
while ($name = $names->fetch_object()) {
echo '"' . $name->rs_name . '",';
}
?>
];
$( "#autocomplete" ).autocomplete({
source: availableTags
});
});
</script>
The question is: How good solution it is?
Personally, I feel that combining JavaScript that should be cached on the client and PHP is bad practice. In the future, it'll be much more difficult to maintain, is slower for the client as it'll have to be downloaded every page load, and results in more http requests (or a larger single http request).
<?php
$names = $db->query("SELECT rs_name FROM names");
$list = array();
while($name = $names->fetch_object()) {
$list[] = $name->rs_name;
}
?>
<script type="text/javascript" src="js/mscript.js"></script>
<script>
// Now, let's initialize our functions on jQuery load
jQuery(function($) {
auto_complete(<?php echo json_encode($list); ?>);
});
</script>
Then, mscript.js will contain:
var auto_complete = (function(auto_list) {
$( "#autocomplete" ).autocomplete({
source: auto_list
});
});
Add additional functions or classes in mscript.js. Then the client only has to download that once and not every page load.
In this example it doesn't seem applicable, but when you add different JS functionality in the future, it'll make the code much more portable and easy to work with.
Edit: As a side note, I believe that some versions of IE have issues with trailing ,
in arrays. json_encode can take care of that for you and also will escape the values for you (in case you have an rs_name with a "
, for example.