I want to fetch data from this public API which takes a parameter. I would like to then display this fetched data in a table.
I also have two buttons backwards and forward which change the parameter for the URL and therefore display a new set of data in the table.
The forward button adds 1 to the parameter and the backwards button substracts 1 from the parameter of the API url.
This is my current code:
HTML code:
<div align="center">
<button style="display:inline" onclick="backFunc();">Back</button>
<p id="gameweek" style="display:inline;"></p>
<button style="display:inline" onclick="forwardFunc();">Forward</button>
<br>
<br>
<table id = "fixtures_table">
<tbody id ="tbody"></tbody>
</table>
</div>
This is my javascript code:
var request = new XMLHttpRequest();
request.withCredentials = true;
var urlparam = "1";
roundnum = 0;
var gameweek;
request.open("GET", "https://api-football-
v1.p.rapidapi.com/v2/fixtures/league/524/Regular_Season_-_" + urlparam);
request.setRequestHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com");
request.setRequestHeader("x-rapidapi-key",
"733394c196mshc5cdb3fe20f1ec5p162525jsnc81f4950b7d6");
var data
request.onload = function () {
data = JSON.parse(this.response);
gameweek = document.getElementById('gameweek');
gameweek.innerHTML = data.api.fixtures[roundnum].round;
if (request.status >= 200 && request.status < 400) {
var tbody = document.getElementById('tbody');
var table = document.getElementById('fixtures_table');
data.api.fixtures.forEach(fixtures => {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + fixtures.homeTeam.team_name + '</td>' +
'<td>' + fixtures.goalsHomeTeam + '</td>' +
'<td>' + "VS" + '</td>' +
'<td>' + fixtures.awayTeam.team_name + '</td>' +
'<td>' + fixtures.goalsAwayTeam + '</td>' +
'<td>' + fixtures.status;
tbody.appendChild(tr);
table.appendChild(tbody);
});
}
console.log(data);
}
function forwardFunc(){
}
function backFunc(){
}
However I am not sure how to make the forward and backwards function fetch the new set of data using the updated parameter and display those results in the table instead of the old ones.
Related
I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:
<root>
<document-id>
<author>Tom Riddle</autor>
<title>abzy</title>
<year>1995</year>
</document-id>
<document-id>
<author>Tom Riddle</autor>
<title>abzy</title>
</document-id>
<document-id>
<author>Tom Riddle</autor>
<year>1995</year>
</document-id>
</root>
I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.
THIS IS THE ASSOCIATED HTML
<body>
<header>
<h1>Reading Data from XML Files</h1>
</header>
<main>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<table id="demo">
</table>
</main>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
myFunction(this);
}
xhttp.open("GET", "books.xml");
xhttp.send();
}
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("document-id");
console.log(x)
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
"</tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
Check for existence before you try to access the children.
function getText(node, tag) {
var elem = node.getElementsByTagName(tag);
return elem ? elem.[0].childNodes[0].nodeValue : '';
}
for (let i = 0; i <x.length; i++) {
var cells = ['author', 'title', 'year'].map(function (tag) {
return "<td>" + getText(x[i], tag) + "</td>";
}).join("");
table += "<tr>" + cells + "</tr>");
}
try this with in line solution to check if tag exist in xml
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("document-id");
console.log(x)
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" + ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue ) +
"</td><td>" +
((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue ) +
"</tr>";
}
document.getElementById("demo").innerHTML = table;
}
I'm trying to get some value over my server using jquery's $.get method and store the result in an object.
What I'm doing is running my function inside a loop:
function renderTabelScheduledEmploye(employees) {
$('#containerDataStaff').empty();
let record = '';
let count = 1;
if (employees.length > 0) {
$.each(employees, function(key, value) {
getFromServerScheduleCount(employees[key].schedule_employee_id);
console.log(scheduleCountData);
record += '<tr>';
record += '<td>' + count + '</td>';
record += '<td>( ' + employees[key].emp_kode + ') - ' + employees[key].emp_full_name + '</td>';
record += '<td>' + scheduleCountData[0].work + '</td>';
record += '<td>' + scheduleCountData[0].offDay + '</td>';
record += '<td>' + scheduleCountData[0].leave + '</td>';
record += '<td>' + scheduleCountData[0].shiftCount + '</td>';
record += '<td>Set Shift</td>';
record += '</tr>';
count++;
});
}
$('#containerDataStaff').append(record);
}
Then I create a function to retrieve JSON data from my server using the $.get function, then store the data result to an object that has been declared:
var scheduleCountData = new Object();
function getFromServerScheduleCount(schedule_employee_id) {
let url = `{{ url('/departement/schedule/manage/schedule/count') }}`;
url = url + '/' + schedule_employee_id + '/get';
let data = {};
$.get(url, function(data) {
let obj = JSON.parse(data);
data.work = obj.work;
data.dayOff = obj.dayOff;
data.leave = obj.leave;
data.shifts = obj.shifts;
scheduleCountData.new = data;
})
}
I can see in the console that the object has filled with the data
[object success to fill][1]
But when i try to access in code like this
scheduleCountData[0]
and log the result to to the console, it shows undefined.
This little bit frustrating for me. I hope someone can help me. Thanks for community.
EDIT :
Sorry i miss
i try to call that object with code like this
scheduleCountData.new
but still undefined on console
Seems youre not waiting for the load to finish before trying to use the data:
// This has a get call, which is async (takes time to load)
getFromServerScheduleCount(employees[key].schedule_employee_id);
// The script will continue, without waiting for the load to finish, so can be empty
console.log(scheduleCountData);
I would suggest adding a callback, like this:
getFromServerScheduleCount(employees[key].schedule_employee_id, function(scheduleCountData) {
console.log(scheduleCountData);
});
function getFromServerScheduleCount(schedule_employee_id, callback) {
$.get(url, function(data) {
// ...
callback(data);
});
}
I am using XAMPP Apache to do XMLHTTP Javascript (AJAX) request from a json file but I am only looping through two(2) entries instead of the entire array four or five (5). I believe there is a problem with my looping code in both my "next" and "previous" functions. Hitting the next button allow me to go ahead and hitting the previous button allows me to go back but only through two(2
function next(xhttp) {
var i = 0,
len;
//var xhttp;
//xhttp = new XMLHttpRequest();
var users = JSON.parse(xhttp.responseText);
len = users.length;
if (i < len - 1) {
i++;
}
var usersText = '';
usersText +=
'<div class="next">' +
'ID: ' + users[i].id + '<br>' +
'Name: ' + users[i].name + '<br>' +
'Email: ' + users[i].email;
document.getElementById("usersNav").innerHTML = usersText;
}
function previous(xhttp) {
var i = 0,
len;
//var xhttp;
//xhttp = new XMLHttpRequest();
var users = JSON.parse(xhttp.responseText);
len = users.length
if (i > 0) {
i--;
}
var usersText2 = '';
usersText2 +=
'<div class="prev">' +
'ID: ' + users[i].id[navigation image][1] + '<br>' +
'Name: ' + users[i].name + '<br>' +
'Email: ' + users[i].email;
document.getElementById("usersNav").innerHTML = usersText2;
}
<button type="button" onclick="loadDoc('users.json',previous)"><<</button>
<button type="button" onclick="loadDoc('users.json',next)">>></button>
I am only getting two entries to toggle through....if I click next and previous. I should be getting all the entries which is about 4-5.
I am learning AJAX and not able to find how to refer a particular row in a table which is fetched from a .json file. Actually I want the respective data on click of the respective edit button in the row. It should be displayed in the <p> tag just below the table.
Heres my script
<script>
function myFunction() //on click function to fetch data from json
{
var counter;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(xhttp.readyState == 4 && xhttp.status == 200)
{
var data = JSON.parse(xhttp.responseText);
mydata(data);
}
};
xhttp.open("GET", "employee.json");
xhttp.send();
counter ++ ;
}
function mydata(data){ //data to be shown and fetch
var output = "<table>";
var output = "<th>Employee Code</th>" +
"<th>Name</th>" +
"<th>Joining Date</th>" +
"<th>Salary</th>"+
"<th>Edit</th>";
//var i in each items[i]
for(var i in data)
{
output += '<tr>' +
'<td>' + data[i].empcode + '</td>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].joining + '</td>'+
'<td>' + data[i].salary + '</td>' +
'<td>' + '<button onclick="edit()">Edit</button>' +
'</tr>';
}
output +="</th>" + "</th>" + "</th>" + "</th>" + "</th>";
output += "</table>";
document.getElementById('demo').innerHTML = output;
function edit(){
document.getElementById("para").innerHTML = data[1].empcode;
}
}
function edit(){ //edit function to display related data from json file. Right now i can only display data which i mentioned in editTextData().
var edit = new XMLHttpRequest();
edit.onreadystatechange = function(){
if(edit.readyState == 4 && edit.status == 200){
var editData = JSON.parse(edit.responseText);
editTextData(editData);
}
};
edit.open("GET", "employee.json", true);
edit.send();
}
function editTextData(textData){
document.getElementById("para").innerHTML = textData[2].empcode;
}
</script>
This is the JSON data :
[{
"empcode" : 1,
"name": "sid",
"joining" : "13 march",
"salary" : 60000
},
{
"empcode" : 2,
"name": "andrew",
"joining" : "15 march",
"salary" : 65000
},
{
"empcode" : 3,
"name": "blake",
"joining" : "18 march",
"salary" : 70000
}
]
This is the html code :
<h1>AJAX Employee</h1>
<div>
<table id="demo"> </table>
</div>
<button onclick="myFunction()" ">Fetch Info</button>
<p id="para"> </p>
This is the result i am getting
Result table after clicking fetch button. When i click any edit button it shows the 3rd employee number
Your edit handler can figure out which button was clicked, which row it belongs to, and which empcode that was. The key is the this value that gets passed into the edit handler.
You're assigning the handler inline, which isn't ideal, so you will need to make a change to that part:
'<td>' + '<button onclick="edit(this)">Edit</button>'
Now the button is being passed into edit as the first parameter, so:
function edit(btn) { //edit function to display related data from json file.
// get the TR that this button is in
var tr = btn.parentNode.parentNode;
// get the collection of tds
var tds = tr.querySelectorAll("td");
// get the contents of the first TD, that should be the empcode
var empcode = tds[0].innerText;
// do whatever you need to with empcode, or the other values in this record
console.log("empcode = " + empcode + ", name = " + tds[1].innerText);
}
I have the following code that gets the data and populates in a table on the fly:
$.ajax({
method: "GET",
url: "/portal/management/fees/" + source_id,
success: function() {
$.getJSON('/portal/management/fees/' + source_id, function(data) {
var table='<table><thead> <tr> <th>Limit</th> <th>Amount</th> <th>Description</th> <th></th> </tr> </thead>';
/* loop over each object in the array to create rows*/
$.each( data, function( index, item){
/* add to html string started above*/
table+='<tr>' +
'<td>' +item.limit +'</td>' +
'<td>' +item.amount +'</td>' +
'<td>' +item.description + '</td>' +
'<td><button class="btn btn-xs btn-default btn-action edit-btn"'+
'id="editBtn"'+
'data-fee-id="'+ item.id+'"'+
'data-fee-amount="'+item.amount+'"'+
'data-fee-limit="'+item.limit+'"'+
'data-fee-description="'+item.decription+'"'+
'data-fee-type="'+item.type+'"'+
'data-fee-vat="'+item.vat+'"'+
'data-toggle="modal"'+
'data-target="#feeModal">'+
'<i class="fa fa-edit"></i>'+
'</button>' +
'</td>' +
'</tr>';
});
$("#source-table").html( table );
});
},
error: function() {
console.log('Error occurred! ' + msg.responseText);
}
});
But I have the button which opens up in a modal and I need to get the data for each one pass to the individual modals for each record. The custom attributes doesn't seem to be working and have I have the following code that I've tried but to no avail.
$(".edit-btn").click(function() {
var fee_id = $(this).attr('data-fee-id');
var amount = $(this).attr('data-fee-amount');
var limit = $(this).attr('data-fee-limit');
var desc = $(this).attr('data-fee-description');
var type = $(this).attr('data-fee-type');
var vat = $(this).attr('data-fee-vat');
$('#feeId').val(fee_id);
$('#amount').val(amount);
$('#limit').val(limit);
$('#desc').val(desc);
$('#type').val(type);
$('#vat').val(vat);
});
So the question is how can I get the data in the modal for each record that has the corresponding button clicked?
Any help/advise greatly appreciated.
In one word.Try
success: function() {
$.getJSON('/portal/management/fees/' + source_id, function(data) {
var table='<table><thead> <tr> <th>Limit</th> <th>Amount</th> <th>Description</th> <th></th> </tr> </thead>';
/* loop over each object in the array to create rows*/
$.each( data, function( index, item){
/* add to html string started above*/
table+='<tr>' +
'<td>' +item.limit +'</td>' +
'<td>' +item.amount +'</td>' +
'<td>' +item.description + '</td>' +
'<td><button class="btn btn-xs btn-default btn-action edit-btn"'+
'id="editBtn"'+
'data-fee-id="'+ item.id+'"'+
'data-fee-amount="'+item.amount+'"'+
'data-fee-limit="'+item.limit+'"'+
'data-fee-description="'+item.decription+'"'+
'data-fee-type="'+item.type+'"'+
'data-fee-vat="'+item.vat+'"'+
'data-toggle="modal"'+
'data-target="#feeModal">'+
'<i class="fa fa-edit"></i>'+
'</button>' +
'</td>' +
'</tr>';
});
$("#source-table").html( table );
$(".edit-btn").click(function() {
var fee_id = $(this).attr('data-fee-id');
var amount = $(this).attr('data-fee-amount');
var limit = $(this).attr('data-fee-limit');
var desc = $(this).attr('data-fee-description');
var type = $(this).attr('data-fee-type');
var vat = $(this).attr('data-fee-vat');
$('#feeId').val(fee_id);
$('#amount').val(amount);
$('#limit').val(limit);
$('#desc').val(desc);
$('#type').val(type);
$('#vat').val(vat);
});
});
},
append your code
$(".edit-btn").click(function() {
var fee_id = $(this).attr('data-fee-id');
var amount = $(this).attr('data-fee-amount');
var limit = $(this).attr('data-fee-limit');
var desc = $(this).attr('data-fee-description');
var type = $(this).attr('data-fee-type');
var vat = $(this).attr('data-fee-vat');
$('#feeId').val(fee_id);
$('#amount').val(amount);
$('#limit').val(limit);
$('#desc').val(desc);
$('#type').val(type);
$('#vat').val(vat);
});
next to $("#source-table").html( table );