Mixed PHP with jQuery AJAX












1














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.










share|improve this question




















  • 1




    As it is written, this yields javascript like $(home).click(function() {.... are there variables corresponding to home, profile, etc. or should those be string literals with CSS selectors like '#home', '.home', etc.?
    – Sᴀᴍ Onᴇᴌᴀ
    Sep 13 '17 at 20:32












  • Yes, I have created variables with those from the html ids. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID
    – Samuel
    Sep 13 '17 at 20:33
















1














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.










share|improve this question




















  • 1




    As it is written, this yields javascript like $(home).click(function() {.... are there variables corresponding to home, profile, etc. or should those be string literals with CSS selectors like '#home', '.home', etc.?
    – Sᴀᴍ Onᴇᴌᴀ
    Sep 13 '17 at 20:32












  • Yes, I have created variables with those from the html ids. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID
    – Samuel
    Sep 13 '17 at 20:33














1












1








1







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.










share|improve this question















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.







javascript php jquery ajax iteration






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 13 '17 at 21:12









Sᴀᴍ Onᴇᴌᴀ

8,33261853




8,33261853










asked Sep 13 '17 at 19:51









Samuel

1639




1639








  • 1




    As it is written, this yields javascript like $(home).click(function() {.... are there variables corresponding to home, profile, etc. or should those be string literals with CSS selectors like '#home', '.home', etc.?
    – Sᴀᴍ Onᴇᴌᴀ
    Sep 13 '17 at 20:32












  • Yes, I have created variables with those from the html ids. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID
    – Samuel
    Sep 13 '17 at 20:33














  • 1




    As it is written, this yields javascript like $(home).click(function() {.... are there variables corresponding to home, profile, etc. or should those be string literals with CSS selectors like '#home', '.home', etc.?
    – Sᴀᴍ Onᴇᴌᴀ
    Sep 13 '17 at 20:32












  • Yes, I have created variables with those from the html ids. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID
    – Samuel
    Sep 13 '17 at 20:33








1




1




As it is written, this yields javascript like $(home).click(function() {.... are there variables corresponding to home, profile, etc. or should those be string literals with CSS selectors like '#home', '.home', etc.?
– Sᴀᴍ Onᴇᴌᴀ
Sep 13 '17 at 20:32






As it is written, this yields javascript like $(home).click(function() {.... are there variables corresponding to home, profile, etc. or should those be string literals with CSS selectors like '#home', '.home', etc.?
– Sᴀᴍ Onᴇᴌᴀ
Sep 13 '17 at 20:32














Yes, I have created variables with those from the html ids. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID
– Samuel
Sep 13 '17 at 20:33




Yes, I have created variables with those from the html ids. They are not just plain words, They would actually be a variable containing the string with the value of their equivalent ID
– Samuel
Sep 13 '17 at 20:33










1 Answer
1






active

oldest

votes


















2















However, I am not sure if this is good practice, or if it should be avoided.




While I don't think it is bad practice, it could be simplified. One technique to simplify it is using event delegation.



For example, the array of tab options could be added to a JavaScript array:



$tab_options = array('home', 'profile', 'news', 'api');
echo 'var tab_options = '.json_encode($tab_options).';';


Then add a click handler to the document and check if the id attribute corresponds to one of those tab options.



$(document).click(function(clickEvent) {
var targetId = clickEvent.target.id;
if (tab_options.indexOf(targetId) > -1) {


In that code Array.indexOf() is used but one could also use Array.contains() though it isn't supported by as many (mostly older) browsers (e.g. IE).



Then to get the equivalent of ucwords(), a solution like from this answer can be used:



var properCaseOption = targetId.replace(/b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
window.top.document.title = properCaseOption;


With this approach, the JavaScript code is not duplicated once for each tab option. Perhaps it may not be a big issue because that code could easily be updated with the PHP code, it would yield a larger HTML/JS page size.



See a demonstration of this in this playground example but note that the AJAX requests won't yield the pages as expected so the code to update the containers has been commented out. However I made a phpfiddle that has the response from the AJAX request utilized.






share|improve this answer



















  • 1




    Clever mate, I appreciate the answer
    – Samuel
    Sep 13 '17 at 21:00











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f175604%2fmixed-php-with-jquery-ajax%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2















However, I am not sure if this is good practice, or if it should be avoided.




While I don't think it is bad practice, it could be simplified. One technique to simplify it is using event delegation.



For example, the array of tab options could be added to a JavaScript array:



$tab_options = array('home', 'profile', 'news', 'api');
echo 'var tab_options = '.json_encode($tab_options).';';


Then add a click handler to the document and check if the id attribute corresponds to one of those tab options.



$(document).click(function(clickEvent) {
var targetId = clickEvent.target.id;
if (tab_options.indexOf(targetId) > -1) {


In that code Array.indexOf() is used but one could also use Array.contains() though it isn't supported by as many (mostly older) browsers (e.g. IE).



Then to get the equivalent of ucwords(), a solution like from this answer can be used:



var properCaseOption = targetId.replace(/b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
window.top.document.title = properCaseOption;


With this approach, the JavaScript code is not duplicated once for each tab option. Perhaps it may not be a big issue because that code could easily be updated with the PHP code, it would yield a larger HTML/JS page size.



See a demonstration of this in this playground example but note that the AJAX requests won't yield the pages as expected so the code to update the containers has been commented out. However I made a phpfiddle that has the response from the AJAX request utilized.






share|improve this answer



















  • 1




    Clever mate, I appreciate the answer
    – Samuel
    Sep 13 '17 at 21:00
















2















However, I am not sure if this is good practice, or if it should be avoided.




While I don't think it is bad practice, it could be simplified. One technique to simplify it is using event delegation.



For example, the array of tab options could be added to a JavaScript array:



$tab_options = array('home', 'profile', 'news', 'api');
echo 'var tab_options = '.json_encode($tab_options).';';


Then add a click handler to the document and check if the id attribute corresponds to one of those tab options.



$(document).click(function(clickEvent) {
var targetId = clickEvent.target.id;
if (tab_options.indexOf(targetId) > -1) {


In that code Array.indexOf() is used but one could also use Array.contains() though it isn't supported by as many (mostly older) browsers (e.g. IE).



Then to get the equivalent of ucwords(), a solution like from this answer can be used:



var properCaseOption = targetId.replace(/b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
window.top.document.title = properCaseOption;


With this approach, the JavaScript code is not duplicated once for each tab option. Perhaps it may not be a big issue because that code could easily be updated with the PHP code, it would yield a larger HTML/JS page size.



See a demonstration of this in this playground example but note that the AJAX requests won't yield the pages as expected so the code to update the containers has been commented out. However I made a phpfiddle that has the response from the AJAX request utilized.






share|improve this answer



















  • 1




    Clever mate, I appreciate the answer
    – Samuel
    Sep 13 '17 at 21:00














2












2








2







However, I am not sure if this is good practice, or if it should be avoided.




While I don't think it is bad practice, it could be simplified. One technique to simplify it is using event delegation.



For example, the array of tab options could be added to a JavaScript array:



$tab_options = array('home', 'profile', 'news', 'api');
echo 'var tab_options = '.json_encode($tab_options).';';


Then add a click handler to the document and check if the id attribute corresponds to one of those tab options.



$(document).click(function(clickEvent) {
var targetId = clickEvent.target.id;
if (tab_options.indexOf(targetId) > -1) {


In that code Array.indexOf() is used but one could also use Array.contains() though it isn't supported by as many (mostly older) browsers (e.g. IE).



Then to get the equivalent of ucwords(), a solution like from this answer can be used:



var properCaseOption = targetId.replace(/b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
window.top.document.title = properCaseOption;


With this approach, the JavaScript code is not duplicated once for each tab option. Perhaps it may not be a big issue because that code could easily be updated with the PHP code, it would yield a larger HTML/JS page size.



See a demonstration of this in this playground example but note that the AJAX requests won't yield the pages as expected so the code to update the containers has been commented out. However I made a phpfiddle that has the response from the AJAX request utilized.






share|improve this answer















However, I am not sure if this is good practice, or if it should be avoided.




While I don't think it is bad practice, it could be simplified. One technique to simplify it is using event delegation.



For example, the array of tab options could be added to a JavaScript array:



$tab_options = array('home', 'profile', 'news', 'api');
echo 'var tab_options = '.json_encode($tab_options).';';


Then add a click handler to the document and check if the id attribute corresponds to one of those tab options.



$(document).click(function(clickEvent) {
var targetId = clickEvent.target.id;
if (tab_options.indexOf(targetId) > -1) {


In that code Array.indexOf() is used but one could also use Array.contains() though it isn't supported by as many (mostly older) browsers (e.g. IE).



Then to get the equivalent of ucwords(), a solution like from this answer can be used:



var properCaseOption = targetId.replace(/b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
window.top.document.title = properCaseOption;


With this approach, the JavaScript code is not duplicated once for each tab option. Perhaps it may not be a big issue because that code could easily be updated with the PHP code, it would yield a larger HTML/JS page size.



See a demonstration of this in this playground example but note that the AJAX requests won't yield the pages as expected so the code to update the containers has been commented out. However I made a phpfiddle that has the response from the AJAX request utilized.







share|improve this answer














share|improve this answer



share|improve this answer








edited Sep 13 '17 at 21:03

























answered Sep 13 '17 at 20:55









Sᴀᴍ Onᴇᴌᴀ

8,33261853




8,33261853








  • 1




    Clever mate, I appreciate the answer
    – Samuel
    Sep 13 '17 at 21:00














  • 1




    Clever mate, I appreciate the answer
    – Samuel
    Sep 13 '17 at 21:00








1




1




Clever mate, I appreciate the answer
– Samuel
Sep 13 '17 at 21:00




Clever mate, I appreciate the answer
– Samuel
Sep 13 '17 at 21:00


















draft saved

draft discarded




















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f175604%2fmixed-php-with-jquery-ajax%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Morgemoulin

Scott Moir

Souastre