Accessing Ajax Response JSON Data in javascript

I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.

    $('#adSpace').change(function () {
        var sel_opt = $(this).val();

        alert(sel_opt);

        var location = null;
        var width = null;
        var height = null;

        $.ajax({
            type: "GET",
            dataType: 'json',
            url: "advertisements-controller.php",
            data: {
                action: "getDimension",
                location: sel_opt
            },
            success: function (response) {

                location = response.banner_location;
                alert(location);


            },
            error: function (xhr) {
                alert("error");
            }
        });

       });

Now i'm getting the data from backend in JSON format like below:

[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]

I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it. Any ideas?

Answers 1

  • response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json. In your case it will be response[0].banner_location


Related Articles