I am new to JSON and JS, and have generated a JSON file to display data via .onclick event. I have gotten so far as generating the JSON data and displaying it on screen, but now I want to style it in a table format, where the elements are able to be seen more clearly. Any help would be awesome!
Here's my JS:
addEventListener("load", set_up_click_handler);
function set_up_click_handler() {
var url = 'http://localhost/Advanced_Web/Final_Project/data/exhibitions.json';
var button = document.getElementById("button");
button.addEventListener("click", click_handler);
function click_handler(event) {
var request = new XMLHttpRequest();
request.open('GET', url);
request.addEventListener("load", response_handler);
request.send();
};
function response_handler() {
if (this.status == 200) {
var json = this.responseText;
var data = JSON.parse(json);
window.localStorage.setItem('exhibitions', JSON.stringify(data));
var div = document.createElement("div");
div.setAttribute("id", "dateOfExhibition");
var list = $('<ul/>');
for (var item in data) {
list.append(
$("<li />").text(item + ": " + data[item])
);
}
$('#exhibitions').append(list);
} else {
alert('An error has occurred.');
}
}
}
And if anyone is feeling extra charitable today, I'm also having this following issue: every time I click on my button, the list displays itself once again. How do I rework the code so that it only displays itself once?
without really knowing the style of the table required please see the example formatting the data into a table with the headers on display, the address with an empty array also has not been handled in this function
var jsonData = { "id": "Pavlov's Dog", "dateOfExhibition": "2018-07-08T22:00:00.000Z", "address": [], "street": "Bergmannstrasse 29", "city": "Berlin", "country": "Deutschland", "zip": "10473"};
function createTable(jsonData){
//create headers
var head = $("<tr />");
var keys = Object.keys(jsonData);
keys.forEach(function(key){
head.append($("<th>"+ key + "</th>"));
});
$("#exhibitionTable").append(head);
//append data (if you have multiple objects in an array like this wrap this in a forEach)
var row = $("<tr />");
for (var item in jsonData){
row.append($("<td>"+ jsonData[item] + "</td>"));
}
$("#exhibitionTable").append(row);
}
$(document).ready(function(){
createTable(jsonData);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table id="exhibitionTable">
</table>
</body>
</html>
Related
I am trying to make a website that shows the weather forecast. It already shows the weather forecast. If I want to enter a city that doesn't exist I want a message to appear. I already tried something with 404 but it doesn't show up in the console log. I hope someone can help me. Thank you in advance!
function getData() {
let apikey = 'private';
var city = document.querySelector('#city').value;
let requestURL = 'https://api.openweathermap.org/data/2.5/forecast?q='+city+'&appid='+apikey+'&units=metric';
let request = new XMLHttpRequest();
request.open('GET', requestURL, true);
request.responseType = 'json';
request.send();
request.onload = function () {
let data = request.response;
addData(data);
var body = document.querySelector('body');
var div = document.createElement('div');
for (var i = 0; i < data.list.length; i += 8) {
// console.log(data.list[i].dt_txt);
div.appendChild( createEL('p',
'<b>Date en time: ' + data.list[i].dt_txt+'<br></b>'+
'City: ' + city+'<br>'+
'Country: ' + data.city.country + '<br>'+
'Temperature: ' +data.list[i].main.temp+'<br>'+
'Weather: ' +data.list[i].weather[0].main));
}
if (XMLHttpRequest == '404'){
console.log("Doesn't exist")
}
var body = document.querySelector('body');
body.appendChild(div);
function createEL(tag, content){
var el = document.createElement(tag);
el.innerHTML = content;
return el;
}
}
}
var button = document.querySelector('#show');
button.addEventListener("click", function (ev) {
ev.preventDefault();
getData();
},false);
function addData(jsonData) {
var city = document.querySelector('#city').value;
var input = document.querySelector('#city');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather</title>
</head>
<body>
<h1>Weather</h1>
City: <input type="text" id="city" name="city" placeholder="city">
<button id="show" name="show">Show</button>
<script src="js/weather.js"></script>
</body>
</html>
XMLHttpRequest will never be equal to 404. It is the constructor function you used to created the object that made the HTTP request!
You need to examine request.status.
You need to check request.status if you are sending status code from API.
let request = new XMLHttpRequest()
console.log(request.status);
To display does not exist you can check the response data length like
if(data.list.length==0)
{
console.log("Does not exists.");
}
I have the following xml document
<?xml version="1.0" ?>
<result searchKeyword="Mathematics">
<video>
<title>Chaos Game</title>
<channel>Numberphile</channel>
<view>428K</view>
<link>http://www.youtube.com/watch?v=kbKtFN71Lfs</link>
<image>http://i.ytimg.com/vi/kbKtFN71Lfs/0.jpg</image>
<length>8:38</length>
</video>
<video>
<title>Australian Story: Meet Eddie Woo, the maths teacher you wish you'd had in high school</title>
<channel>ABC News (Australia)</channel>
<view>223K</view>
<link>http://www.youtube.com/watch?v=SjIHB8WzJek</link>
<image>http://i.ytimg.com/vi/SjIHB8WzJek/0.jpg</image>
<length>28:08</length>
</video>
<video>
<title>Ham Sandwich Problem</title>
<channel>Numberphile</channel>
<view>557K</view>
<link>http://www.youtube.com/watch?v=YCXmUi56rao</link>
<image>http://i.ytimg.com/vi/YCXmUi56rao/0.jpg</image>
<length>5:53</length>
</video>
<video>
<title>Magic Square Party Trick</title>
<channel>Numberphile</channel>
<view>312K</view>
<link>http://www.youtube.com/watch?v=aQxCnmhqZko</link>
<image>http://i.ytimg.com/vi/aQxCnmhqZko/0.jpg</image>
<length>3:57</length>
</video>
<video>
<title>The 8 Queen Problem</title>
<channel>Numberphile</channel>
<view>909K</view>
<link>http://www.youtube.com/watch?v=jPcBU0Z2Hj8</link>
<image>http://i.ytimg.com/vi/jPcBU0Z2Hj8/0.jpg</image>
<length>7:03</length>
</video>
</result>
I have created this html file which has an AJAX call to get the xml file but it return all the values as "undefined"
<html>
<head>
<title>A7-Question2</title>
<script>
function getSearch()
{
// create an XMLHttpRequest
var xhttp = new XMLHttpRequest();
//create a handler for the readyState change
xhttp.onreadystatechange = function() {
readyStateChangeHandler(xhttp);
};
//get XML file by making async call
xhttp.open("GET", "A7.xml", true);
xhttp.send();
}
// handler for the readyState change
function readyStateChangeHandler(xhttp){
if (xhttp.readyState == 4){
// readyState = 4 means DONE
if(xhttp.status == 200){
// status = 200 means OK
handleStatusSuccess(xhttp);
}else{
// status is NOT OK
handleStatusFailure(xhttp);
}
}
}
// XMLHttpRequest failed
function handleStatusFailure(xhttp){
// display error message
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
// XMLHttpRequest success
function handleStatusSuccess(xhttp){
var xml = xhttp.responseXML;
// print XML on the console
console.log(xml);
// parse the XML into an object
var searchResult = parseXML(xml);
// print object on the console
console.log(searchResult);
// display the object on the page
display(searchResult);
}
// parse the XML into an object
function parseXML(xml){
var resultElement = xml.getElementsByTagName("result")[0];
//create a receipt object to hold the information in the xml file
var searchResult = {};
searchResult.searchKeyword= resultElement.getAttribute("searchKeyword");
var videoElements = xml.getElementsByTagName("video");
//create an array to hold the items
searchResult.videoArray = [];
for(var i=0; i< videoElements.length; i++){
var video = {};
video.title = videoElements[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
video.channel = Number(videoElements[i].getElementsByTagName("channel")[0].childNodes[0].nodeValue);
video.view = Number(videoElements[i].getElementsByTagName("view")[0].childNodes[0].nodeValue);
video.link = Number(videoElements[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
video.image = Number(videoElements[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
searchResult.videoArray.push(video);
};
return searchResult;
}
// display the searcg result object on the page
function display(searchResult){
var html = "<p>searchKeyword: Mathematics</p>";
for(var i=0; i<searchResult.videoArray.length; i++){
var video = searchResult.videoArray[i];
html += "title: " + searchResult.title + "<br/>";
html += "channel: " + searchResult.channel + "<br/>";
html += "view: " + searchResult.view + "<br/>";
html += "link: " + searchResult.link + "<br/>";
html += "image: " + searchResult.image + "<br/>";
html += "length: " + searchResult.length + "<br/>";
}
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = html;
}
</script>
</head>
<body>
<button onclick="getSearch()">Get Search Result</button>
<div id="display"></div>
</body>
</html>
Is the problem with my success function? Is it returning null because it hasn't returned all the values or something due to how AJAX runs?
Thanks heaps for any help
There's a lot of code to go over and a working snippet can't be produced because we can't put the XML file here.
This answer is making an assumption that your response from the XMLHttpRequest is null and the problem does not lie in any of your parsing functions.
It also seems that you're over complicating the request process by passing it around to many functions when it's quite simple itself.
Here is an example I made locally that correctly logged the XML to the console:
<!doctype html>
<html>
<head>
<title>A7-Questions2</title>
</head>
<body>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xml = xhttp.responseXML;
// Logs just fine for me. You can do your parsing here.
console.log(xml);
}
};
xhttp.onerror = function() {
// Display error message.
var displayDiv = document.getElementById('display');
displayDiv.textContent = 'XMLHttpRequest failed status: ' + xhttp.status;
};
xhttp.open('GET', './path/to/xml.xml');
xhttp.send();
</script>
</body>
</html>
Notice: New to SharePoint
I was able to get peoplepicker div to work but I need help getting the name value or display name to post inside my SharePoint column named Person. Currently, once the user submits the Person column comes in blank. Sorry for the lack of knowledge, just a bit lost.
$(document).ready(function() {
initializePeoplePicker('peoplePickerDiv');
});
function initializePeoplePicker(peoplePickerElementId) {
// Create a schema to store picker properties, and set the properties.
var schema = {};
schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
//This value specifies where you would want to search for the valid values
schema['SearchPrincipalSource'] = 15;
//This value specifies where you would want to resolve for the valid values
schema['ResolvePrincipalSource'] = 15;
schema['AllowMultipleValues'] = true;
schema['MaximumEntitySuggestions'] = 50;
// schema['Width'] = '780px';
// Render and initialize the picker.
// Pass the ID of the DOM element that contains the picker, an array of initial
// PickerEntity objects to set the picker value, and a schema that defines
// picker properties.
this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
}
function getUserInfo() {
// Get the people picker object from the page.
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
var userInfo = '';
for (var i = 0; i < users.length; i++) {
var user = users[i];
for (var userProperty in user) {
userInfo += userProperty + ': ' + user[userProperty] + '<br>';
}
}
$('#resolvedUsers').html(userInfo);
// Get user keys.
var keys = peoplePicker.GetAllUserKeys();
$('#userKeys').html(keys);
// Get the first user's ID by using the login name.
getUserId(users[0].Key);
}
// Get the user ID.
function getUserId(loginName) {
var context = new SP.ClientContext.get_current();
this.user = context.get_web().ensureUser(loginName);
context.load(this.user);
context.executeQueryAsync(
Function.createDelegate(null, ensureUserSuccess),
Function.createDelegate(null, onFail)
);
}
function ensureUserSuccess() {
$('#userId').html(this.user.get_id());
}
function onFail(sender, args) {
alert('Query failed. Error: ' + args.get_message());
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="format-detection" content="telephone=no" />
<title>Package Delivery</title>
<link rel="stylesheet" href="../SiteAssets/Package%20Delivery/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../SiteAssets/Package%20Delivery/css/style.css">
<!--[if IE]>
<script src="http://html5shi../SiteAssets/javier/v.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div id="contact" method="post">
<div class="row">
<div class="col-md-12">
Recipient's Name
<div id="peoplePickerDiv"></div>
<!-- <input class="form-control input-sm" name="Sender" id="sender" placeholder="Enter Person to Notify">-->
</div>
I'm taking they values by using javascript file:
/*=========================================
* SharePoint Repeating Field Form Template
=========================================*/
/*TODO:
Connect Profile Properties
Test Submission
Make everything generic
Post to GitHub
*/
var baseURI = "https://berkeleycollege365.sharepoint.com/sites/"; // root name
var siteName = "central-support-services";
var listName = "PackageDelivery"; // list name
$( document ).ready(function() {
// getUserProperties();
});
function getUserProperties(){
var requestUriCom = "https://berkeleycollege365.sharepoint.com/_api/SP.UserProfiles.PeopleManager/getmyproperties";
$.ajax({
url: requestUriCom,
headers:{"Accept":"application/json; odata=verbose"},
contentType:'application/json; odata=verbose',
Type: 'GET',
success: onSuccessUser,
error: function (data) {console.log(data);}
})
}
function onSuccessUser(data){
//console.log(data);
//Parse the return allll the way down.
var parse = data.d.UserProfileProperties.results[4].Value;
}
$('[data-ssd-dynamic-wrapper]').ssdDynamicRows({
clear_warning: function(row) {
row.find('[data-validation] [data-case]').removeClass('show');
row.find(':input').removeClass('warning');
},
other_elements: {
'[data-validation]' : 'data-validation'
}
});
$('#submit').on('click', function(event) {
console.log("working");
event.preventDefault();
$(this).find('[data-case="required"]').removeClass('show');
$('#result').empty();
var inputs = $(this).find(':input').removeClass('warning');
inputs.each(function() {
if ($(this).val() === '') {
$(this).addClass('warning')
.closest('[data-ssd-dynamic-field]')
.find('[data-case="required"]')
.addClass('show');
}
});
/************************
You probably dont have to edit this.
This will account for any new fields in the repeating section and add the correct key value pairs.
Again, probably dont have to edit this.
Placed all of the stuff you SHOULD edit under the next comment break.
*************************/
var a = [];
var fullString = "";
//We iterate through each row...
$('.itemRow').each(function(i){
//setting up our second array
var b = [];
//We are in our rows, so now we will find and iterate through the inputs within that row
$(this).find(':input').each(function(i, key){
//getting the value
var c = this.value;
//getting the name and splitting off the unique identifier so we can use it as our key name
var d = $(this).attr('name');
d = d.substr(0,d.indexOf('-'));
//pushing the information into our secondary array
b.push([d,c]);
});
var i = 0;
var key;
var val;
var obj = {};
//Here, we will take the values from our secondary array and form our objects
//We also create our string here
for (i;i < b.length;i++){
key = b[i][0];
obj[key] = b[i][1];
val = b[i][1];
fullString += key + ":" + val + " ";
}
//Push the objects into our main array
a.push(obj);
//Toss on a line break for our rich text fields
fullString+="<br>";
});
//Extend our array
var convertedA = $.extend({},a);
//Turn everything into a JSON object so we can store and retrieve it
//var convertedB = JSON.stringify(convertedA);
/*******************************
********************************
Here you can choose what to pass for submission.
********************************
*******************************/
createItem(fullString);
location.reload() // Reloads screen after hitting submit button
});
function createItem(multilineString) {
console.log("First String"+multilineString);
//Setting up the URL to the list we will post to.
var itemUrl = baseURI + siteName + "/_api/web/lists/getByTitle('"+ listName +"')/items";
//This applies the correct content type for this list item. You can find the function for this towards the end of the script.
var itemType = "SP.Data.PackageDeliveryListItem";//getListItemType(listName);
//Hardcoding the metadata we are passing as this can only serve one function.
var item = {
"__metadata": { "type": itemType },
"Title":"Title", //Setup your data here
"date":$("#date").val(),
"from":$("#from").val(),
"departmentChoice":$("#departmentChoice").val(),
"shippedTo":$("#shippedTo").val(),
"shippedFrom":$("#shippedFrom").val(),
"carrier":$("#carrier").val(),
"method":$("#method").val(),
"Date_x0020_Received":$("#ReceivedDate").val(),
"Person": $("#peoplePickerDiv").val(),
//"Person": $.get("getUserInfo()"),
"Details": multilineString,
"Form_x0020_Filled_x0020_By":$("#filledBy").val(),
"Date_x0020_Filled":$("#dateFilled").val(),
"Email_x0020_Sent_x0020_On":$("#emailSent").val(),
"deliveryOther":$("#deliveryOther").val()
};
//Turn everything into a JSON object
var body = JSON.stringify(item);
//Post the item
$.ajax({
url: itemUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: body,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data){console.log(data);},
error: function (data) {console.log(data);}
});
}
// Getting the item type for the list
function getListItemType(name) {
return"SP.Data." + name[0].toUpperCase() + name.substring(1) + "ListItem";
}
To set user or group field column using REST API, please check the format for user field value as below:
single-valued user field: '<user field name>' : <user id>
multi-valued user field: '<user field name>' : { 'results': [<array of user ids>]}
Example:
Single user field value
var item = {
"__metadata": { "type": itemType },
"Title":"Title", //Setup your data here
"PersonId": 10
};
Multiple user field value
var item = {
"__metadata": { "type": itemType },
"Title":"Title", //Setup your data here
"PersonId": {"results": [10,11,12] } //multi-valued User field value
};
So, please get the users id from People Picker before add list item to list using REST API.
I use Javascript. I want to get RSS data by API google (this link: http://www.javascriptkit.com/dhtmltutors/googleajaxfeed.shtml ), then insert the data into a Array (Global variable). But my global variable can not save data.
Inside rssfeedsetup() function, ARR_DATA (Global Array) have data. However, after load rssfeedsetup() function, ARR_DATA have no data.
Please show me, how to insert data to global variable in this case.
My code:
Head:
<head>
<title>TEST API FEED RSS</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
</script>
</head>
Body:
<body>
<div id="feeddiv"></div>
<script type="text/javascript">
var ARR_DATA = []; // **I want to insert data into this array**
var feedurl = "http://rss.slashdot.org/Slashdot/slashdot";
var feedlimit = 4;
function rssfeedsetup() {
var feedpointer = new google.feeds.Feed(feedurl); //Google Feed API method
feedpointer.setNumEntries(feedlimit); //Google Feed API method
feedpointer.load(displayfeed); //Google Feed API method
}
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
var arr_Temporary = [];
for (var i = 0; i < thefeeds.length; i++) {
arr_Temporary[0] = thefeeds[i].title;
arr_Temporary[1] = thefeeds[i].link;
// insert RSS data into ARR_DATA.
ARR_DATA.push(arr_Temporary);
console.log('value before:', ARR_DATA); // check value of ARR_DATA, there have data exist.
}
}
}
window.onload = function () {
rssfeedsetup(); // call function
console.log('value2 after:', ARR_DATA); // check value of ARR_DATA, there is no data.
};
console.log('value2 after:', ARR_DATA); //check value of ARR_DATA, there is no data.
</script>
</body>
I have got value console:
image of firebug on firefox
Ps: Why ARR_DATA no contain data after load function rssfeedsetup()?
You can push data into the array like this:
function displayfeed(result) {
if (!result.error) {
var thefeeds = result.feed.entries;
for (var i = 0; i < thefeeds.length; i++) {
var feed = {
title: thefeeds[i].title,
link: thefeeds[i].link
};
ARR_DATA.push(feed);
}
console.log(feed);
}
}
Hope it helps
I am new to javascript and am creating a piechart which loads data from a comma separated file data.txt but I cannot see anything in the browser when I open the html file.
data.txt consists the following data -
United States,9252
China,1882
Japan,1809
Germany,1322
United Kingdom,1122
India,984
My html code is-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>amCharts examples</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="amcharts/amcharts.js" type="text/javascript"></script>
<script type="text/javascript">
var chart;
var dataProvider;
window.onload = function() {
createChart();
loadCSV("data.csv");
}
// method which loads external data
function loadCSV(file) {
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
}
else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
// load
request.open('GET', file, false);
request.send();
parseCSV(request.responseText);
}
// method which parses csv data
function parseCSV(data){
//replace UNIX new lines
data = data.replace (/\r\n/g, "\n");
//replace MAC new lines
data = data.replace (/\r/g, "\n");
//split into rows
var rows = data.split("\n");
// create array which will hold our data:
dataProvider = [];
// loop through all rows
for (var i = 0; i < rows.length; i++){
// this line helps to skip empty rows
if (rows[i]) {
// our columns are separated by comma
var column = rows[i].split(",");
// column is array now
// first item is date
var country = column[0];
// second item is value of the second column
var visits = column[1];
// third item is value of the fird column
// create object which contains all these items:
var dataObject = {country:country, visits:visits};
// add object to dataProvider array
dataProvider.push(dataObject);
}
}
// set data provider to the chart
chart.dataProvider = dataProvider;
// this will force chart to rebuild using new data
chart.validateData();
}
function createChart(){ // PIE CHART
chart = new AmCharts.AmPieChart();
// title of the chart
chart.addTitle("Visitors countries", 16);
chart.titleField = "country";
chart.valueField = "visits";
chart.sequencedAnimation = true;
chart.startEffect = "elastic";
chart.innerRadius = "30%";
chart.startDuration = 2;
chart.labelRadius = 15;
chart.pullOutEffect = "elastic";
chart.pullOutDuration = 1;
// the following two lines makes the chart 3D
chart.depth3D = 10;
chart.angle = 15;
// WRITE
chart.write("chartdiv");
}
</script>
</head>
<body>
<div id="chartdiv" style="width:600px; height:400px;"></div>
</body>
I have taken the code from http://blog.amcharts.com/2011/03/amcharts-javascript-tutorials-part-2.html and changed it according to piechart.
Please tell me what am I doing wrong.
I have placed data.txt in the same folder as the html file and have not hosted the file on a web server
You're calling loadCSV to load data.csv, but you said your data is in data.txt.
You should try to update your JS, Chrome throws this error : "AmCharts.AmPieChart is not a functioncreateChart # Pie Charts.html:75window.onload # Pie Charts.html:15"
Try to Use DATALOADER :
AmCharts.makeChart("chartdiv", {
"type": "pie",
"dataLoader": {
"url": "data/pie.csv",
"format": "csv",
"delimiter": ",",
"useColumnNames": true
},