Search code examples
jqueryrefactoringjquery-post

JQuery: Want to refactor some Jquery code to make it simple and easy


I have the following code in JQuery, On DOM Ready it runs, its job is to post data to my PHP file, and return the returned data into the specified div. I am using 5 bits of code, most of it is repeating it self over again. I wanted to refactor this somehow, can someone make this code into a couple of lines is possible?

Basically, on change of a select box element, it runs and does the code.

// First Level Categories
    $("#slct_firstCat").live("change", function(){
    $("#div_secondCat").fadeOut();
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_firstCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 1},
        function(data){
            $("#div_secondCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Second Level Categories
    $("#slct_secondCat").live("change", function(){
    $("#div_thirdCat").fadeOut();
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_secondCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 2},
        function(data){
            $("#div_thirdCat").fadeIn().html(data);
           });
    // End of Function getCats
    });


// Third Level Categories
    $("#slct_thirdCat").live("change", function(){
    $("#div_fourthCat").fadeOut();
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_thirdCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 3},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Fourth Level Categories
    $("#slct_fourthCat").live("change", function(){
    $("#successCats").remove();

    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_fourthCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 4},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

// Fifth Level Categories
    $("#slct_fifthCat").live("change", function(){
    $("#successCats").remove();
    var actionRequested = "AJAX_getCats";
    var url = "index.php";
    var catId = $("#slct_fifthCat").val();

    $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 5},
        function(data){
            $("#div_fourthCat").fadeIn().html(data);
           });
    // End of Function getCats
    });

You can see most the code is repeated many times, the only things that change are the element names and the category level in the post action.

I hate having this huge chunk of code in my JS script, used over and over again, surely someone out-there can help reduce this to a few lines or a function if possible?

--------------------------- EDIT ---------------------------

This is the php code that sends the data back from the $.post, if this helps.
Each select box is inside its own div when posted to html, The DIVs are on the html and not ajax'd in.
Basically, I want to navigate down to a category using these select box's to easily visualize where I am in the category nav. The $data variable, is an object which has an array of the category data requested.
(Sorry Im pressed for time g2g work, else I would have cleaned up the code more)

<?php if (isset($data->CategoryArray->Category->LeafCategory) == 1){ ?>

    <div id='successCats' align='center'>
    <b>Your Selected Category is:</b><br/>
    <select id='selectedCategory' name='selectedCategory' size='1'>
    <option value='<?=$data->CategoryArray->Category->CategoryID."'>".$data->CategoryArray->Category->CategoryName;?></option>
    </select>
    </div>

<?php } else {  ?>
<?php
$catLevel = $_POST['categoryLevel'];
if ($catLevel == 1){
    echo "<select id=\"slct_secondCat\" name=\"slct_secondCat\" size=\"15\">";
} elseif ($catLevel == 2) {
    echo "<select id=\"slct_thirdCat\" name=\"slct_thirdCat\" size=\"15\">";
}
  else if($catLevel == 3){
  echo "<select id=\"slct_fourthCat\" name=\"slct_fourthCat\" size=\"15\">";
} else if($catLevel == 4){
  echo "<select id=\"slct_fifthCat\" name=\"slct_fifthCat\" size=\"15\">";
}

    $cats = array_slice($data->CategoryArray->Category,1);
    foreach ($cats as $cats){
    if ($cats->CategoryID == $cats->CategoryParentID){
    // Do Nothing - Get rid of the first header Cat
    } else {
    $option =  "<option value=\"" . $cats->CategoryID . "\">" . $cats->CategoryName;
    if(!isset($cats->LeafCategory)){
        $option .= " >";
    }

    $option .= "</option>";

    echo $option;
    }
    } // End of For each

} // End of First If Else
?>
<?php echo "</select>"; ?>

Solution

  • But it looks like this block just needs to be turned into a function

    function LevelCategories(levelSelector, levelSelector2) {
        $("#slct_secondCat").live("change", function(){
        $("#div_thirdCat").fadeOut();
        $("#div_fourthCat").fadeOut();
        $("#successCats").remove();
    
        var actionRequested = "AJAX_getCats";
        var url = "index.php";
        var catId = $(levelSelector).val();
    
        $.post(url, {AJAX_Action: actionRequested, categoryId: catId, categoryLevel: 2},
            function(data){
                $(levelSelector2).fadeIn().html(data);
               });
        // End of Function getCats
        });
    }
    

    Then just call the function with the correct selectors (I may have those wrong...

    LevelCategories("#slct_firstCat", "#slct_secondCat");
    LevelCategories("#slct_secondCat", "#slct_thirdCat");
    LevelCategories("#slct_thirdCat", "#slct_fourthCat");
    LevelCategories("#slct_fourthCat", "#slct_fourthCat");
    LevelCategories("#slct_fifthCat", "#slct_fourthCat");