简体   繁体   中英

jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?

If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?

function getSubCategories() {
    var id = $("#category").prop('selectedIndex');
    var selectedCategory = $("#category").val();
    //should change this into a response from AJAX and grab the slug from there, this is fine for now.
    var slugOfCategory = convertToSlug(selectedCategory);
    id++;
    console.log('here');
    $.ajax({
        method: 'GET', // Type of response and matches what we said in the route
        url: '/product/get_subcategories', // This is the url we gave in the route
        data: {
            'id': id
        }, // a JSON object to send back
        success: function(response) { // What to do if we succeed
            $("#sub_category option").remove(); //Remove all the subcategory options
            $.each(response, function() {
                $("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
            });
            $("#category_slug").attr('value', slugOfCategory);
        },
        error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
}

function getCategories() {
    var id = $("#type").prop('selectedIndex');
    var selectedType = $("#type").val();
    //should change this into a response from AJAX and grab the slug from there, this is fine for now.
    var slugOfType = convertToSlug(selectedType);
    console.log(slugOfType);
    //add one to the ID because indexes dont start at 0 as the id on the model
    id++;
    $.ajax({
        method: 'GET', // Type of response and matches what we said in the route
        url: '/product/get_categories', // This is the url we gave in the route
        data: {
            'id': id
        }, // a JSON object to send back
        success: function(response) { // What to do if we succeed
            $("#category option").remove(); //Remove all the subcategory options
            $.each(response, function() {
                $("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
            });
            $("#type_slug").attr('value', slugOfType);
        },
        error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
}

function convertToSlug(Text) {
    return Text
        .toLowerCase()
        .replace(/ /g, '_')
        .replace(/[^\w-]+/g, '');
}

$(document).ready(function() {

    var firstCatgegory = $("#category").val();
    var slugOfFirstCategory = convertToSlug(firstCatgegory);
    $("#category_slug").attr('value', slugOfFirstCategory);

    var firstType = $("#type").val();
    var slugOfFirstType = convertToSlug(firstType);
    $("#type_slug").attr('value', slugOfFirstType);

    $("#type").change(getCategories());

    $("#category").change(getSubCategories());
});

Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)

This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.

To make this work you need to put your code within the success callback function instead.

<script>
function getSubCategories()
{
     var id= $("#category").prop('selectedIndex');
     $.ajax({
          method: 'GET',
          url: '/product/get_subcategories',
          data: {'id' : id}, 
          success: function(response){ 
             // DO SOMETHING HERE
          },
          error: function(jqXHR, textStatus, errorThrown) { }
    });
}

$( document ).ready(function() {

    // This is also wrong. Currently you're passing
    // whatever is returned from getSubCategories
    // (which is undefined) as the callback function
    // that the "change" event will call. This instead
    // should be the reference to the function. Which
    // in this case is getSubCategories

    $("#category").change(getSubCategories);
});

Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.

<script>
$(document).ready(function(){
$("#category").change(function(){
    getSubCategories();
});
$("#type").change(function(){
    getCategories();
});
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM