Zulhilmi Zainudin
Zulhilmi Zainudin

Reputation: 9365

jQuery Ajax each() Not Working

I'm new with jQuery. I try to fetch some data using Ajax and I want to loop it and insert it inside result div.

The data not displayed in the result div.

var url = 'http://node.globalresearch.my/mybanjir/ws.BencanaJKR.php?function=getBencanaJKR&output=json&state_code=06';

var result_div = $('#result');

$.ajax({
    url: url,
    type: 'GET',
    success: function (d) {
        $.each(d, function (i, val) {
        result_div.append(val.id);
        });
    },
    beforeSend: function () {
        $("#loading").show();
    },
    complete: function () {
        $("#loading").hide();
    }
});

DEMO: http://jsfiddle.net/w7jhaqz1/

Am I doing any mistake?

One more, how to access individual id? Say I want to only show status for id 1, how to do that?

Upvotes: 0

Views: 1224

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

You need to add dataType: 'json' to your $.ajax call. The URL you are accessing - which, interestingly supports CORS - isn't sending the right Content-type header.

That header tells jQuery how to process the data. It's not sending the correct header, so jQuery doesn't know to parse it as JSON. Adding dataType: 'json' tells jQuery to assume it's JSON and parse it.

$.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function (d) {
        $.each(d, function (i, val) {
            result_div.append(val.id);
        });
    },
    beforeSend: function () {
        $("#loading").show();
    },
    complete: function () {
        $("#loading").hide();
    }
});

Upvotes: 1

Related Questions