Ibrahim İnce Ibrahim İnce - 1 month ago 8
JSON Question

retrieving multiple JSON files with jquery

I want to retrieve data from multiple json files.I am able to append data to the table from one of the json file. But when I wanted to pull the data from multiple json files it wont work. My code is:

var uri = 'sharepointmodel.json';
var uri2 = 'navisioncustomer.json';

function find(sharepointmodel) {
var info = $('#KUNDE').val()
$("#loader").show();
$.getJSON(uri).done(function (data) {
var item = data.filter(function (obj) {
return obj.name === info || obj.ID === info;
})[0];

if (typeof item ==='undefined'){
alert("Ukendt navn eller ID");
}
else if (typeof item !== 'undefined' || item !== null) {
$("table.table").append("<tr><td> " + item.name + item.url + "</td></tr>");
}
}).fail(function (jqXHR, textStatus, err) {
$('#ERROR').text('Kan ikke oprette forbindelse til serveren!');
}).always(function (){
$("#loader").hide();
});
}

function find(navisioncustomer) {
var info2 = $('#KUNDE').val()
$("#loader").show();
$.getJSON(uri2).done(function (data) {
var item = data.filter(function (obj) {
return obj.name === info2 || obj.ID === info2;
})[0];

if (typeof item ==='undefined'){
alert("Ukendt navn eller ID");
}
else if (typeof item !== 'undefined' || item !== null){
$("table.table2").append("<tr><td> " + item.name + item.phone + "</td></tr>");
}
}).fail(function (jqXHR, textStatus, err) {
$('#ERROR').text('Kan ikke oprette forbindelse til serveren!');
}).always(function (){
$("#loader").hide();
});
}

Answer

Both of your function names are same, find(). That's why just one function is getting called and your data is getting appended from only one file.

Either have different function names or have one function and pass uri variable to it e.g.

  function find(json_uri) {
    var info = $('#KUNDE').val()
    $("#loader").show();
    $.getJSON(json_uri).done(function(data) {
        var item = data.filter(function(obj) {
            return obj.name === info || obj.ID === info;
        })[0];
        if (typeof item === 'undefined') {
            alert("Ukendt navn eller ID");
        } else if (typeof item !== 'undefined' || item !== null) {
            $("table.table").append("<tr><td> " + item.name + item.url + "</td></tr>");

        }
    }).fail(function(jqXHR, textStatus, err) {
        $('#ERROR').text('Kan ikke oprette forbindelse til serveren!');
    }).always(function() {
        $("#loader").hide();
    });
}

To append data to both you will have to make two calls

find(uri);
fin(uri2);