R.MILLER R.MILLER - 7 months ago 17
Javascript Question

minimizing ajax/jquery functions for dynamic content

I am unsure if I am going about dynamically updating the content on this site properly. As I get deeper into building the site I have began to realize that my functions are going to be crazy..

The code is working however I am adding a new function for each menu item. I was looking for a way to simplify that. Would it be possible to somehow use one function to handle the changing of the content for each of the onclick events I've setup? Maybe its time to pick up a book, any suggestions are welcomed.

HTML:

<ul id="mainNav">
<li><a href="#" onclick="contentAjax()">HOME</a></li>
<li><a href="#" onclick="contentAjaxDocs()">DOCS</a></li>
<li><a href="#" onclick="contentAjaxServers()">SERVERS</a></li>
<li><a href="#" onclick="contentAjaxMonitors()">MONITORS</a></li>
</ul>


Javascript:

function contentAjax() {
var request = $.ajax({
url: '/resources/templates/home.php',
type: "GET",
dataType: "html"
});

request.done(function(msg) {
$("#content").html(msg);

});

request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});

var request2 =
$.ajax({
url: '/resources/templates/homerightPanel.php',
type: "GET",
dataType: "html"
});

request2.done(function(msg) {
$("#rightPanel").html(msg);

});

request2.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});

}

Answer

Something like this seems more efficient.

HTML

 <ul id="mainNav">
    <li><a href="url/to/home">HOME</a></li>
    <li><a href="url/to/docs">DOCS</a></li>
    <li><a href="url/to/servers">SERVERS</a></li>
    <li><a href="url/to/monitors">MONITORS</a></li>
 </ul> 

Javascript

$('#mainNav li a').click(function(e){
    e.preventDefault(); //So the page doesn't load the URL
    var url = $(this).attr('href');
    contentAjax(url);
});
function contentAjax(url) {
    var request = $.ajax({
        url: url,
        type: "GET",
        dataType: "html",
        success: function(msg){
            $("#content").html(msg);
        },error: function(jqXHR,textStatus){
            alert( "Request failed: " + textStatus );
        }
    });
}

The added benefit of my method (and the way you should do things) is the pages at those URLs should work without javascript. So if the user has Javascript disabled they site will work and if the do have javascript your site will still work. Your way, if a use has Javascript disabled your site is literally broken.

Additionally you shouldn't use the onclick attribute (Why is using onClick() in HTML a bad practice?)

Comments