I have a quick script I came up with and I was wondering if this is a bad idea.
First let me explain what I want to do. I want to create a dynamic script which will add custom AJAX calls for whatever tab element I need it to. For instance, if the user clicks on Profile
, then I want to load profile.php
from my files.
This is simple enough, however, I have a lot of calls, and I came up with a quick fix. I am creating an array with all the scripts I need to call in PHP, and when the page loads PHP it creates AJAX call functions from the array list:
<?php
$tab_options = array('home', 'profile', 'news', 'api');
foreach ($tab_options as $option)
{
?>
$(<?php echo $option; ?>).click(function() {
$.ajax({
type: "POST",
url: "_template/<?php echo $option; ?>.php",
dataType: "html",
success: function(response){
window.top.document.title = '<?php echo ucwords($option); ?>';
window.history.pushState("string", "<?php echo ucwords($option); ?>", "?tab=<?php echo $option; ?>");
$("#<?php echo $option; ?>").html(response);
},
error: function(){
console.log("Problem found!");
}
});
});
<?php
}
?>
So in this case I would have PHP loop 4 times over the code, and create the 4 functions for me. It works well, and I am able to switch between tabs smoothly. However, I am not sure if this is good practice, or if it should be avoided.
$(home).click(function() {...
. are there variables corresponding tohome
,profile
, etc. or should those be string literals with CSS selectors like'#home'
,'.home'
, etc.? \$\endgroup\$id
s. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID \$\endgroup\$