Novice
Novice

Reputation: 77

Fetching a response using Jquery

Good day how can I fetch this ajax response using jquery? This is my current jquery code

    function fetch(select){
        if ($(select).val() !== null) {
            var rank= $("#rank");
            $.getJSON('{{route("json_style_rank")}}', {id: $(select).val()}, function(data) {
                $("#rank option").remove();
                $.each(data.ranks, function(){
                    rank.append('<option value="'+ this.id +'">'+ this.name +'</option>')
                });
                rank.select2().val(null).trigger('change');
            });
        }
    }

and this is the ajax response

[,…]
0:{id: 118, organization_id: 6035, school_id: null, picture: "", name: "Hapkido", description: "Kicks",…}
created_at:"2017-05-22 15:34:32"
description:"Kicks"
id:118
name:"Hapkido"
organization_id:6035
picture:""
ranks:[,…]
0:{id: 561, style_id: 118, level: 1, name: "1st Dan ", type: "solid", tip_enabled: 0, tip_sequential: 1,…}
1:{id: 562, style_id: 118, level: 2, name: "1st Gup", type: "double", tip_enabled: 1, tip_sequential: 1,…}
2:{id: 563, style_id: 118, level: 3, name: "2nd Gup", type: "double", tip_enabled: 1, tip_sequential: 1,…}
3:{id: 564, style_id: 118, level: 4, name: "3rd Gup", type: "solid", tip_enabled: 1, tip_sequential: 1,…}
4:{id: 565, style_id: 118, level: 5, name: "4th Gup", type: "solid", tip_enabled: 1, tip_sequential: 0,…}
5:{id: 917, style_id: 118, level: 6, name: "5th Gup", type: "solid", tip_enabled: 0, tip_sequential: 1,…}
school_id:null
updated_at:"2017-05-22 15:34:32"

enter image description here

I want to get the ranks id and name

Upvotes: 0

Views: 255

Answers (1)

Sandesh Gupta
Sandesh Gupta

Reputation: 1195

Try this.

function fetch(select){
    if ($(select).val() !== null) {
        var rank= $("#rank");
        $.getJSON('{{route("json_style_rank")}}', {id: $(select).val()}, function(data) {
            $("#rank option").remove();
            //Get and loop over only first element of the response array
            $.each(data[0].ranks, function(){
                rank.append('<option value="'+ this.id +'">'+ this.name +'</option>')
            });
            rank.select2().val(null).trigger('change');
        });
    }
}

Update: To iterate over all the elements in the response array, you'll need one more $.each loop

$.each(data, function(){
    //Get and loop over only first element of the response array
    $.each(this.ranks, function(){
        rank.append('<option value="'+ this.id +'">'+ this.name +'</option>')
    });
});

Upvotes: 1

Related Questions