shows all the attributes, I need only name weight growth, eye color, skin color and gender
url = "https://swapi.co/api/people";
function heroes () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
console.log(data); // see object
}
document.getElementById('demo').innerHTML = xhr.responseText; // write info
};
xhr.open("get", url, true);
xhr.send();
}
You're started by showing the request and parsing into a JSON object. That's a good start!
Now, you need to iterate each result (you can use a for loop) and render the property.
I've built an example, here's the code:
Html:
<div id="output">
</div>
Javascript:
var url = "https://swapi.co/api/people";
function heroes() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
var tableContent = '<table>'
tableContent += "<thead><tr>";
tableContent += "<td>Name</td>";
tableContent += "<td>Height</td>";
tableContent += "<td>Mass</td>";
tableContent += "<td>Eye Color</td>";
tableContent += "<td>Skin Color</td>";
tableContent += "<td>Gender</td>";
tableContent += "</tr></thead>";
for(var i=0;i<data.results.length;i++) {
var person = data.results[i];
tableContent += "<tr>";
tableContent += "<td>" + person.name + "</td>";
tableContent += "<td>" + person.height + "</td>";
tableContent += "<td>" + person.mass + "</td>";
tableContent += "<td>" + person.eye_color + "</td>";
tableContent += "<td>" + person.skin_color + "</td>";
tableContent += "<td>" + person.gender + "</td>";
tableContent += "</tr>";
}
tableContent += "</table>"
document.getElementById('output').innerHTML = tableContent; // write table
}
// document.getElementById('demo').innerHTML = xhr.responseText; // write info
};
xhr.open("get", url, true);
xhr.send();
}
heroes();
Here's a pen, if you want to see it live.
Related
One more thing is here that if I use the alert() at end of the ajax code the code is working fine. here whatever the ajax response comes has to be appended to the existing table.
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);for (var i = 0; i < jsonArray.length-1; i++) {
html += "<tr id=\"rowitem" + i + "\"><td id=\"rownum"+i+ "\" style=\"display:none;\">" + i + "</td><td> " + jsonArray[i].Clientgroup + " </td>";
html += "<td>" + jsonArray[i].hostgroup + "</td>";
html += "<td>" + jsonArray[i].server + "</td>";
html += "<td>" + jsonArray[i].Group + "</td>";
html += "<td>" + jsonArray[i].user + "</td>";
html += "<td>" + jsonArray[i].ticket + "</td>";
html += "<td>" + jsonArray[i].requesttype + "</td>";
$.ajax({
url : "BulkValidateServlet",
type : "POST",
data : {clientgroup: jsonArray[i].Clientgroup, hostgroup: jsonArray[i].hostgroup, server: jsonArray[i].server
},success : function(response){
//alert("i in of ajax:"+i);
status = response;
if (status) {
//alert("outside if: " + status);
//$('<img src=\'images/check_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/check_mark.png' height='20' width='20'/></td>";
} else {
//alert("outside else: " + status);
//$('<img src=\'images/cross_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/cross_mark.png' height='20' width='20'/></td>";
}
console.log("Data: " + status);
// alert("Data: " + status );
//return status;
}
});
console.log("outside: " + status);
alert();
}
document.getElementById('tbodyLeads').innerHTML = html;
}
You can try adding
async: false
to your ajax attributes.
Refer to this link.
my json array is like that which was received in html page how it can be display in a table ? means iteration .plz help? i am new .
[
{"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"},
{"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"},
{"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"}
]
Iterate over the array and display it in a table:
var jsonObject = [
{studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"},
{studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"},
{studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"}
];
var output = "<table>";
for (var i = 0, len = jsonObject.length; i < len; i++) {
var line = jsonObject[i];
output += "<tr>";
output += "<td>" + line.studentId + "</td>";
output += "<td>" + line.firstName + "</td>";
output += "<td>" + line.lastName + "</td>";
output += "<td>" + line.year + "</td>";
output += "<td>" + line.course + "</td>";
output += "</tr>";
}
output += "</table>";
document.getElementById(...).innerHTML = output;
Well first of all JSON is (JavaScript Object Notation). Same JS, just a litlte bit different syntax for object notation.
You need to use AJAX in order to receive JSON data from other file, just have a look:
var xhr = new XMLHttpRequest();
var url = "myJSON.json"; // your JSON text file
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var myResponse = JSON.parse(xhr.responseText);
display(myResponse); // send array to function
}
}
xhr.open("GET", url, true);
xhr.send(null);
function display(arr) {
var myTable = "<table>"; // create a table variable
for (var i = 0; i < arr.length; i++) { // loop through array
myTable += "<tr>";
myTable += "<td>" + arr[i].studentId + "</td>";
myTable += "<td>" + arr[i].firstName + "</td>";
myTable += "<td>" + arr[i].lastName + "</td>";
myTable += "<td>" + arr[i].year + "</td>";
myTable += "<td>" + arr[i].course + "</td>";
myTable += "</tr>";
}
myTable += "</table>";
document.getElementById("myAwesomeTable").innerHTML = myTable; // display the final result in to html
}
Use AJAX in order to open your JSON text file, it could be .txt, .json and etc.
Use JSON.parse() to convert your JSON text to Array
Send that Array to function
Create a table and hold everything in variable like a text
Loop through array
Display your table in to html
I need to implement drag and drop feature form one table to another and vise versa.
This is my function where i get transactions to particular IBAN number, I also have the same function which retrieves users transaction which are hidden.
function getAllTransactions(iban) {
var iban = $("#ibanSelection").val();
var username = $("#hiddenusername").val();
var url = 'http://localhost:64300/api/BankAccountApi/GetUserTransaction/?iban=' + iban;
var table = "<table id=\"table1\">";
if ((username != "") && (iban !="")) {
$.getJSON(url, function (data) {
table += "<tr class=\"ibanSelection\">";
table += "<th>My IBAN</th>";
table += "<th>Send to IBAN</th>";
table += "<th>Transfer Date</th>";
table += "<th>Amount</th>";
table += "</tr>";
$.each(data, function (key, val) {
table += "<tr class=\"draggable_tr\">";
table += "<td>" + val.My_Iabn + "</td>";
table += "<td>" + val.Iban_To + "</td>";
table += "<td>" + val.Transfer_Date + "</td>";
table += "<td>" + val.Amount_Transferd + "</td>";
table += "</tr>";
});
table += "</table>";
$("#divResult2").html(table);
});
}
}
Just use the jQueryUI Sortable feature.
Here's the complete example + documentation. Very easy.
Also this example shows your case:
http://jqueryui.com/sortable/#connect-lists
I'm using Facebook Javascript SDK and FB.api. I read public pages' posts and wanted to show it on my website. So I made the call with FB.api and got the response. But while I try to show them by Facebook Embed System it just didn't show up.
Here is my code
FB.api("/" + PageId + "/posts",
{
access_token: getCookie("access_token"),
since: From,
until: To,
fields: "id,likes.summary(true).limit(0),comments.summary(true).limit(0),shares,link",
limit: LoadLimit,
date_format: "U",
},
function (res) {
$("#load_post").attr("disabled", false).attr("value", "Load Posts");
if (typeof res.error === 'undefined') {
if (res.data.length > 0) {
for (var i = 1; i <= res.data.length; i++) {
var NewData = res.data[i - 1];
var Id = NewData.id.split("_")[1];
var CreatedTime = NewData.created_time;
var Likes = NewData.likes.summary.total_count;
var Comment = NewData.comments.summary.total_count;
var Share = 0;
var Link = NewData.link;
if (typeof NewData.shares !== 'undefined') {
Share = NewData.shares.count;
}
var Data = "";
Data += "<tr>";
Data += "<td>" + i + "</td>";
Data += "<td><div id='" + Id + "' class='fb-post' data-href='" + Link + "' data-width='350'></div></td>";
Data += "<td>" + CreatedTime + "</td>";
Data += "<td>" + Likes + "</td>";
Data += "<td>" + Comment + "</td>";
Data += "<td>" + Share + "</td>";
Data += "<td></td>";
Data += "<td></td>";
Data += "<td></td>";
Data += "</tr>";
$("#data_area").append(Data);
FB.XFBML.parse(document.getElementById(Id));
}
} else {
alert("No data found.");
}
} else {
alert("Error occured.\n" + res.error.message);
}
});
Even I tried "FB.XFBML.parse" but lately checking the documentation I found that it has no effect on Embed Post.
I checked the console and found no error or something.
Please help me out.
I'm trying to get a JSON input with AJAX and load it in a select control.
but when I run it :\ It stuck on "Downloading the recipes....".
anyone see the problem maybe? (I tried couple of changes but nothing work so far)
1 more issue can anyone think on a shorter way to do the
ConvertToTable(targetNode)
cuse it's way to long and complex, I think :\
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
document.getElementById("span").style.visibility = "visible";
document.getElementById("span1").style.visibility = "hidden";
document.getElementById("button").style.visibility = "hidden";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
result = xmlhttp.responseText;
result = eval('(' + result + ')');
txt = "<select onchange='ShowRecipeDetails(this)'>";
for (i = 0; i < result.length; i++) {
txt = txt + "<option VALUE=" + result[i].recipe + ">" + result[i].recipe + "</option>";
}
txt = txt + "</select >";
document.getElementById("span").style.visibility = "hidden";
document.getElementById("span1").style.visibility = "visible";
document.getElementById("myDiv").innerHTML = txt;
}
}
xmlhttp.open("POST", "http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=json", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send();
}
function ShowRecipeDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var field = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://food.cs50.net/api/1.3/recipes?&output=json&id=" + field,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data[0]));
}
});
}
function ConvertToTable(targetNode) {
var table = "<table border = 1 borderColor =green>";
table += "<tr>";
table += "<td>" + "ID" + "</td>";
table += "<td>" + targetNode.id + "</td>";
table += "</tr>";
table += "<td>" + "Ingredients:" + "</td>";
table += "<td>" + targetNode.ingredients + "</td>";
table += "</tr>";
table += "<td>" + "Name:" + "</td>";
table += "<td>" + targetNode.name + "</td>";
table += "</tr>";
table += "<td>" + "Size:" + "</td>";
table += "<td>" + targetNode.size + "</td>";
table += "</tr>";
table += "<td>" + "Unit" + "</td>";
table += "<td>" + targetNode.unit + "</td>";
table += "</tr>";
table += "<td>" + "VEGETARIAN:" + "</td>";
table += "<td>" + targetNode.VEGETARIAN + "</td>";
table += "</tr>";
table += "</tr>";
table += "</table>"
return table;
}
</script>
and the HTML:
<button id="button" type="button" onclick="loadXMLDoc()" >Get all recipes</button>
<br />
<span id="span" style="visibility:hidden">Downloading the recipes....</span>
<span id="span1" style="visibility:hidden">Please choose a recipe ID to view</span>
<div id="jsonDiv"></div>
<div id="myDiv"></div>
<div id="TableDiv"></div>
The HarvardFood API also supplies a JSONP version. So if you change your URL to this:
http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=jsonp&callback=parseResponse
you can create a parseResponse function to handle the data that comes back, and you can do the AJAX by inserting a script tag.
The problem is that you're running afoul the Same Origin Policy.
I see that you've updated the question to use jQuery AJAX. That offers a jsonp data type, which might be easier than adding a script tag.