I have a simple function that is supposed to display either of two sets of data in a HTML table. This data comes from an external domain using an ajax request. Both sets of data have been parsed and are stored in two variables, named animalData and fruitNvegData.
I have two buttons which run the buildTable() function. I need to make each button pass the relevant data into the function. I know how to do this in JavaScript but that way doesn't work with jQuery. I have read many examples of passing arguments/parameters into a function but none of the methods work for me. I have tried a few variations on this kind of thing, but no joy:
$("animalButton").click({ param: animalData }, buildTable);
For now I am using animalData in the each() loop to make sure everything else is working. I have found many similar questions here on StackOverflow, but none of these work either. Like using bind() for instance.
This is my entire jquery code. So how do I pass the relevant data with each button click into the function?
var animalData;
var fruitNvegData;
$(document).ready(function() {
$.ajax({
dataType: 'json',
url: "http://www.adweb.agency/interview/api/animals",
type: 'get',
success: function (data) {
animalData = $.parseJSON(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("animal data unavailable at this time");
}
});
$.ajax({
dataType: 'json',
url: "http://www.adweb.agency/interview/api/fruitveg",
type: 'get',
success: function (data) {
fruitNvegData = $.parseJSON(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fruit n Veg data unavailable at this time");
}
});
});
function buildTable(){
var i = 0;
var table = '<table class="mainTable"><tr><th>item</th><th>image</th><th>description</th></tr>';
$.each(animalData, function (idx, obj) {
table += ('<tr>');
table += ('<td>' + obj.Title + '</td>');
table += ('<td><img src="' + obj.ImageURLs.Thumb + '"></td>');
table += ('<td>' + obj.Description + '</td>');
table += ('</tr>');
});
table += '</table>';
$("#tableContainer").html(table);
};
$("#animalButton").click(buildTable);
$("#fruitNvegButton").click(buildTable);