jQuery AJAX function call

50
May 19, 2017, at 6:58 PM

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)

Answer 1

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>
Answer 2

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

READ ALSO
How to get current state data in jquery datatable after searching sorting etc?

How to get current state data in jquery datatable after searching sorting etc?

Let I have five rows in jquery datatableAfter searching no of rows becomes say 3

66
Attach click event dynamically as below on document ready [on hold]

Attach click event dynamically as below on document ready [on hold]

The web page has 30 buttons and I loop 30 timesBut sometimes button 1 and 2 not working

50
Setting CSS class to a specific div with specific style attribute

Setting CSS class to a specific div with specific style attribute

I'm currently redoing a website (http://wwwvins-de-fronton

46