jQuery Ajax loads URL multiple times, how do I unbind/rebind properly?

Posted by gmoz22 on Stack Overflow See other posts from Stack Overflow or by gmoz22
Published on 2010-12-29T13:27:18Z Indexed on 2010/12/29 13:53 UTC
Read the original article Hit count: 176

Filed under:
|
|

I load a SELECT element via Ajax (list of brands), get its selected value (brand id) and load another SELECT via another Ajax URL (list of templates for currently selected brand).

Here's my code:

$(document).ready( function() {


    // DO NOT cache Ajax calls
    $.ajaxSetup ({ cache: false });

    // loader
    var ajax_load = "Loading...";

    //  Brands List URL
    var loadBrandUrl = "getBrandsList.php";
    //  Templates List URL
    var loadTemplateUrl = "getTemplatesList.php";

    $("#brandslistSelect").html(ajax_load).load(loadBrandUrl)
        .ajaxComplete(function(){  // Brands select loaded

        /* Load Templates SELECT the first time since no .change() has happened */
            var selectedBrand = $("#brandslistSelect option:selected").attr("value");  // get the value
            console.log(selectedBrand);  // Log selected brand to console
            // get Templates select, commented for now since it does an infinite loop
            // $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } );
        /* End initial load template */

        /* On interaction with the Brands SELECT */
        $("#brandslistSelect").change(function () {  // on interaction with select

            selectedBrand = $("#brandslistSelect option:selected").attr("value");  // get the value
            // get Templates SELECT
            $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } )
        });
        /* End interaction with the Brands SELECT */

    });


});

It returns selectedBrand in the console 3 times :
selectedBrand = undefined
selectedBrand = undefined
selectedBrand = 101

Now, if I uncomment the following line, same output as above but it also loads the templates URL indefinitely :

// $("#templateslistSelect").html(ajax_load).load(loadTemplateUrl, { BrandId: selectedBrand } );

Any idea how I could modify this code to make it work as intended?

Thanks for your help stackOverflow community!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about AJAX