Problem using $.ajax method of jquery

When we use $.ajax method then sometime we use this in side success method we get unexpected error because in $.ajax method in success property this has different meaning it refers to xmlhttprequest object other then we are expecting. Here is an example and solution for that:
Example:

    $("#location").change(function () {

            if ($(this).val() == "-1") {
                $("#category").prop('disabled', 'disabled');
            }        
            var that = this;

            $.ajax({
                type: "POST",
                url: "/Home/Category",
                data: JSON.stringify({ projectId: $("#project").val(), locationId: $(this).val() }),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    $('#category').empty();
                    $('#category').prop("disabled", false);
                    $("#category").append("<option value='-1'>--Select Category--</option>");                
                    if (data.length == 0) {
                        $("#category").prop('disabled', 'disabled');
                    } else {
                        for (i = 0; i < data.length; i++) {
                            $("#category").append('<option value=' + data[i].CategoryId + '> ' + data[i].CategoryName + '</option>');
                        }
                    }
                    // disable if category not selected.
                    if ($(that).val() == "-1") {
                        $("#category").prop('disabled', 'disabled');
                    }
                }
            });

In the above example you can see that I have stored this in that variable and used inside success.
  

Comments

Popular posts from this blog

Access Violation Exception