HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptMinor

Fail-proof AJAX

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
ajaxprooffail

Problem

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;
});

});

Solution

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.

Context

StackExchange Code Review Q#36881, answer score: 5

Revisions (0)

No revisions yet.