8
\$\begingroup\$

I'm working on a page using AJAX that will get an entire .php page when the navigation button is clicked. I have that set up and working right. But this is my first time using AJAX, so I'm not sure what the best practices are and what I can do to prevent failures and display error messages.

  $(document).ready(function() {

//set your initial page when website loads
$("#content-container").load("content/corporate.php");

// content container load content based on nav tab clicked
$("#nav-tabs-list li").click(function() {
    var page = $("a", this).attr("href"); // get the url of the tab clicked
    $("#content-container").load("content/" + page); // load content
    return false;
});




// sidebar container load content
$("#sidebar-container #sidebar-content-container").load("content/sidebar-content/poll-faq.php"); // set your sidebar initial tab
$("#sidebar-container #sidebar-tabs-container a").click(function() {
    var page = $(this).attr("href"); //get the url of the tab clicked
    $("#sidebar-container #sidebar-content-container").load("content/sidebar-content/" + page); //load content
    return false;
});

});
\$\endgroup\$

3 Answers 3

5
\$\begingroup\$

There isn't too much wrong. Your containers (#sidebar-container and #sidebar-content-container) really shouldn't need to be accessed by Ids, but more-so classes. For those types of DOM elements, utilize classes.

\$\endgroup\$
2
5
\$\begingroup\$

I am puzzled by the way you add a content/ or content/sidebar-content/ prefix to the href attributes to form the URL to load. Why don't you render the page such that the href already contain the correct URL to load?

You don't need to comment every line of code. Just one comment per "paragraph" of code is sufficient.

Also, fix your indentation.

\$\endgroup\$
5
\$\begingroup\$

Sometimes you don't need to write comments when your code is clear enough. For example, you have :

// content container load content based on nav tab clicked
$("#nav-tabs-list li").click(function() {
    var page = $("a", this).attr("href"); // get the url of the tab clicked
    $("#content-container").load("content/" + page); // load content
    return false;
});

Just by reading the line $("#content-container").load("content/" + page); I can understand that you are loading the content. You don't need to repeat yourself in a comment. Comment should help understand the code, not repeat it.

Also note that comments can be "dangerous", there is no guarantee that when the code change you will update the comment. Be sure that the comments add value.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.