Inserting data from fetch into a HTML div - javascript

I'm having a problem getting data from my fetch response into a div. The data comes into the console just fine, but I can't get it to update the div.
<html lang="">
<head>
<meta charset="UTF-8">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="phand">
<button id="deal" class="btn">Deal!</button>
</div>
<script type="text/javascript" src="{% static 'blackjack/play.js' %}"></script>
</body>
</html>
(function () {
function deal() {
fetch('/deal')
.then(response => response.json())
.then(data => {
console.log(data)
var card1Rank = data[0];
var card1Suit = data[1];
var card2Rank = data[2];
var card2Suit = data[3];
$("#phand").append('<acidjs-xdeck-card rank=' + card1Rank + 'suit=' + card1Suit + '></acidjs-xdeck-card>');
});
};
$('#deal').on('click', function() {
deal();
});
}());
I want the javascript to insert the response from the fetch request into the "phand" element on the page, I can see the data coming through in the console, but it doesn't alter the contents of the page.

maybe you need to convert data to string with JSON.stringify() , try to append like
$("#phand").append('<acidjs-xdeck-card rank=' + JSON.stringify(card1Rank) + 'suit=' + JSON.stringify(card1Suit) + '></acidjs-xdeck-card>');

The problem was that I had the "phand" div inside another "wrapper" div.
I changed the js to:
$('#wrapper').find('#phand').append('<acidjs-xdeck-card rank=' + JSON.stringify(card1Rank) + 'suit=' + JSON.stringify(card1Suit) + '></acidjs-xdeck-card>');
and it worked as expected.

Related

How to update html document using feather js?

I have a service that I call after every 5 secs to return data from postgres table, now I want this data to be displayed on html document
app.js
const stats=app.service('test_view');
// console.log(stats);
function getstats(){
stats.find().then(response=>{
console.log('data is ',response.data)});};
setInterval(function() {
getstats();
}, 5000);
// console.log(stats);
stats.html
<!DOCTYPE html>
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>
Everything is running fine and I am getting results in console, I am using feather.js now I want these results to be displayed in div tag of html.Please help me in this regard.
You need to call the feathers service from the browser. You can do this a number of different ways (as a REST call, with the feathers client, etc.).
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/core-js/2.1.4/core.min.js"></script>
<script src="//unpkg.com/#feathersjs/client#4.0.0-pre.3/dist/feathers.js"></script>
<script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script>
// #feathersjs/client is exposed as the `feathers` global.
const app = feathers();
app.configure(feathers.rest('http://localhost:3000').axios(axios));
app.service('test_view').find();
})
.then(data => {
// do something with data
});
</script>
</head>
<body></body>
</html>
A lot of this depends on what (if anything) you're using for your front-end implementation. This sets up a minimal feathersjs/client using axios for REST, with no authentication, and calls your service (on port 3000) and gets the payload.
To do this every 5 seconds is outside the scope of feathers and up to how you build your web app.
Here is a working example of how you could change the contents of that div when you get data back from your remote call.
// Simulate your remote call... ignore this part.
const stats = {}
stats.find = () => new Promise((resolve, reject) => resolve({
data: 'here is some data ' + new Date().toLocaleTimeString('en-US')
}));
// Div you want to change.
const resultsDiv = document.getElementById('stats');
// Get the data
function getstats () {
stats.find().then(response => {
console.log('data is ', response.data);
// Update the contents of the div with your data.
resultsDiv.innerHTML = response.data;
});
}
setInterval(function() {
getstats();
}, 1000);
<html>
<head>
<title>Stats</title>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id='stats'>
</div>
</body>
</html>

AJAX/JSON with possible Jquery event

I am trying to make it so when the user clicks on the name of a person in the list, the box of data on the right side of the screen fills with the description from my JSON file.
I want to make it so that clicking any list item runs an actual AJAX request. The data returned from that request must then be used to fill the box on the right side of the page.
Any ideas or previous thread you could lead me to would be very appreciated. I've tried many things and have not succeeded.
Can I somehow make each word on the list a clickable element? Maybe with event listener?
Thanks,
Heres my code which is is 3 separate files whis are "html file, javascript file and a json file"
<!DOCTYPE html>
<hmtl lang="en">
<head>
<meta charset="utf-8" />
<title>AJAX</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
<script src="jquery.js" type="application/javascript"></script>
<script src="ajax.js" type="application/javascript"></script>
</head>
<body>
<div id="loaded-data"></div>
<div id="result-box"></div>
</body>
</hmtl>
/* ajax.javascript file */
'use strict';
$(function() {
let request = $.ajax({
method: 'GET',
url : 'people.json',
dataType: 'json',
});
request.done(function(data) {
let list = data.body.list;
let resultBox = $('#result-box');
let unorderedList = $('<ul>');
resultBox.append(unorderedList);
console.log(data);
for (let person of list) {
let listItem = $('<li>');
listItem.text(person.name);
listItem.attr('data-url', person.links[0].href);
unorderedList.append(listItem);
}
});
request.fail(function(response) {
console.log('ERROR: ' + response.statusText);
});
});
{
"links":[{"rel":"self","href":"http://www.philart.net/api/people.json"},{"rel":"parent","href":"http://www.philart.net/api.json"}],
"head":{"title":"People","type":"listnav"},
"body":{
"list":[
{"name":"Adam","links":[{"rel":"self","href":"http://www.philart.net/api/people/325.json"}]},
{"name":"Abigail Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/157.json"}]},
{"name":"John Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/410.json"}]},
{"name":"Samuel Adams","links":[{"rel":"self","href":"http://www.philart.net/api/people/439.json"}]},
{"name":"Lin Zexu","links":[{"rel":"self","href":"http://www.philart.net/api/people/347.json"}]},
{"name":"James A. Zimble","links":[{"rel":"self","href":"http://www.philart.net/api/people/345.json"}]},
{"name":"Doris Zimmerman","links":[{"rel":"self","href":"http://www.philart.net/api/people/171.json"}]}
]
}
}
You just need a handler like this:
let displayPersonData = (person) => {
console.log(person)
}
Then, while rendering list of person, you add event listener like below:
for (let person of list) {
let listItem = $('<li>');
listItem.text(person.name);
listItem.attr('data-url', person.links[0].href);
unorderedList.append(listItem);
listItem.on('click', () => {
displayPersonData(person)
});
}
You can add class to <li> tags so they act like hyperlink. And customize displayPersonData to do what you want.
As Doug Nguyen stated, you will need an event handler.
let displayPersonDescription = person => {
let html = '';
html += person.links.reduce((a, c) => {
//put your formating logic in here
//i.e.
return a + `${c.href}`;
}, '');
html += person.body.art.reduce((a, c) => {
//additional formating logic here
}, '');
// continue this pattern for all the sections you want to include
//...
// Finally load the data into the loaded-data div
$("#loaded-data").html(html);
}
Here is the updated section of your code to implement the handeler
for (let person of list) {
//clear the loaded data div
$(#loaded-data).html('');
let listItem = $('<li>');
listItem.text(person.name);
listItem.attr('data-url', person.links[0].href);
unorderedList.append(listItem);
listItem.on('click', function () {
$.ajax({
method: 'GET',
url: this.dataSet.url,
dataType: 'json',
})
.done(displayPersonDescription(person))
.fail(failureData => console.log(`Error: ${JSON.stringify(failureData)}`));
});
}

YouTube Data API v3 Using Javascript

I am kind of new to writing code and using API's. I am not entirely sure why my program is not working the way I would like it to.
What I want this to do is provide the search results in the console before I can move onto what I would like it to do next; however, I don't think anything is being searched.
According to this: https://developers.google.com/youtube/v3/docs/search/list#http-request, the only required parameter is "part," so I think I did everything right? Probably not though, because from what I can tell, nothing is being searched when I try to search for a term.
Here is my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<section>
<form id="search-term">
<p>Enter Name:<br/>
<input id="query" type="text" name="Name"/><br/>
<hr/>
<input type="button" value="Enter here"/>
</p>
<div id="search-results">
</div>
</form>
</section>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
JavaScript:
$(document).ready(function(){
$('#search-term').submit(function(event){
event.preventDefault();
var searchTerm = $('#query').val();
getRequest(searchTerm);
});
function getRequest(searchTerm){
var params = {
"q": "searchTerm",
"part": 'snippet',
"type": 'video',
"key": 'I was advised to keep my key private, so I edited this part out'
}
url = 'https://www.googleapis.com/youtube/v3/search';
$.getJSON(url, params, function(data){
showResults(data.items);
})
}
function showResults(results){
var html = "";
$.each(results, function(index,value){
html += '<p>' + value.snippet.thumbnails.high.url + '</p>' + '<p>' + 'https://www.youtube.com/watch?v=' + value.id.videoId + '</p>' + '<hr/>';
console.log(value.snippet.thumbnails.high.url);
console.log(value);
})
$('#search-results').html(html);
}
})
You probably want data.items instead of data.search
I don't see any mention of a 'search' parameter under the "Response" section listed in their documentation. See the response properties here: https://developers.google.com/youtube/v3/docs/search/list#response
Therefore, you can probably see some output if you console.log(data); instead of data.search
I recommend you check out Google's Javascript API Client Library. It might not be the best solution for you, but it's worth a try. Download on GitHub
Example using gapi.client.youtube.search.list:
// After the API loads, call a function to enable the search box.
function handleAPILoaded() {
$('#search-button').attr('disabled', false);
}
// Search for a specified string.
function search() {
var q = $('#query').val();
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet'
});
request.execute(function(response) {
var str = JSON.stringify(response.result);
$('#search-container').html('<pre>' + str + '</pre>');
});
}

Looping through inner jquery accordion fields

Is there a way to create a loop for the and statements inside an jquery accordion , so I can iterate through my JSON.
The code below has the JSON working, so I want the data from the JSON to fill my jquery accordion. Just don't know how to work around the h3 and div tags that teh accordion needs.
<html>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<head>
<link rel="stylesheet" href="jquery-ui-1.8.23.custom/development-bundle/themes/base/jquery.ui.all.css">
<script src="jquery-ui-1.8.23.custom/development-bundle/jquery-1.8.0.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.core.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.selectable.js"></script>
<script src="jquery-ui-1.8.23.custom/development-bundle/ui/jquery.ui.accordion.js"></script>
<link rel="stylesheet" href="jquery-ui-1.8.23.custom/development-bundle/demos/demos.css">
<script type='text/javascript' src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script>
$(function() {
$( "#accordion" ).accordion();
});
</script><script>
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON(ReturnPlacesJSON.php, function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
var latlng = new google.maps.LatLng(val.xcoord, val.ycoord);
var title = (val.title)?val.title:""
var icon = 'http://shanewmiller.com/Specials/images/beermug.png';
var special = val.Description;
var end = (val.endtime)?val.endtime:""
var start = (val.starttime)?val.starttime+" - ":""
var day = (val.day)?val.day:""
var html = val.name + val.address + special + day + start + end;
$('<h3 />').html(special).appendTo('#accordion');
$('<div />').html(val.name + ' ' + val.address).appendTo('#accordion');
});
});
});
</script>
</head>
<body>
<div id="accordion">
</div>
</body></html>
What you are trying to do is to create h3 and divs, inside the accordion div
What $('#accordion > h3').each() and $('#accordion > div').each() do is iterating through h3 and divs already inside the accordion, which are none.
What you in fact need to do is iterate through the json - and you do it by calling $.each(data, ...) - and then for each item, create a new h3 and a new div with that content.
You create element using jQuery with something like this:
$('<h3 />').html(special).appendTo('#accordion');
$('<div />').html(val.name + ' ' + val.address).appendTo('#accordion');
I believe the rest of the code must be fine tuned. For instance, I'm not sure that calling accordion(), and after that populating the div gives you the desired effect.

Jquery load remote page element according to a string in current page url

I'm new in Jquery, I would like to have Jquery code to get the current page url and if the url contains certain string then load remote element.
example:
i have the page urls like this:
"http://......./Country/AU/result-search-to-buy"
"http://......./Country/CA/result-search-to-buy"
"http://......./Country/UK/result-search-to-buy"
the part "/Country/AU" is what I need to determine which page element I should load in, then if "AU" I load from "/state-loader.html .state-AU", if "CA" I load from "/state-loader.html .state-CA"
I have a builtin module "{module_pageaddress}" to get the value of the current page url, I just dont know the Jquery logic to let it work.
I expect something like this:
if {module_pageaddress} contains "/Country/AU/"
$('#MyDiv').load('state-loader.html .state-AU');
if {module_pageaddress} contains "/Country/CA/"
$('#MyDiv').load('state-loader.html .state-CA');
please help and many thanks.
Here is some code:
<!DOCTYPE html>
<html>
<head>
<title>jQuery test page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
function stateURL() {
var startOfResult = '../../state-loader.html #state-';
var match = (/(?:\/Country\/)(AU|US|CA|UK)(?:\/)/).exec(window.location.pathname);
if (match) {
return startOfResult + match[1];
} else {
return startOfResult + 'AU';
}
}
</script>
</head>
<body>
Link 1
<div id="content">content will be loaded here</div>
</body>
</html>
And the file to load the different content for the states:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="state-US">Go USA!</div>
<div id="state-CA">Go Canada!</div>
<div id="state-AU">Go Australia!</div>
<div id="state-UK">Go United Kingdom!</div>
</body>
</html>
See it work here:
http://www.quirkscode.com/flat/forumPosts/loadElementContents/Country/US/loadElementContents.html
Replace .../US/... with .../AU/..., etc. to see how it behaves.
Original post where I got the ideas/original code:
http://frinity.blogspot.com/2008/06/load-remote-content-into-div-element.html
You can try
var countryCode = ... // parse the country code from your module
$('#yourDiv').load('state-loader.html .state-' + countryCode);
See more examples of .load() here.
As far as pulling the url path you can do the following
var path_raw = document.location.path,
path_array = path_raw.split("/");
Then, you could do something like this:
$.ajax({
url: "./remote_data.php?country=" + path_array[0] + "&state=" + path_array[1],
type: "GET",
dataType: "JSON",
cache: false,
success: function(data){
// update all your elements on the page with the data you just grabbed
}
});
Use my one line javascript function for getting an array of the URL segments: http://joshkoberstein.com/blog/2012/09/get-url-segments-with-javascript
Then, define the variable $countrySegment to be the segment number that the country code is in.
For example:
/segment1/segment2/CA/
(country code would be segment 3)
Then, check if the 3rd array index is set and if said index is either 'CA' or 'AU'. If so, proceed with the load, substituting in the country-code segment into the .html filename
function getSegments(){
return location.pathname.split('/').filter(function(e){return e});
}
//set what segment the country code is in
$countrySegment = 3;
//get the segments
$segments = getSegments();
//check if segment is set
//and if segment is either 'AU' or 'CA'
if(typeof $segments[$countrySegment-1] !==undefined && ($segments[$countrySegment-1] == 'AU' || $segments[$countrySegment-1] == 'CA')){
$countryCode = $segments[$countrySegment-1];
$('#target').load('state-loader.html .state-' + $countryCode);
}
var result= window.location.pathname.match(/\/Country\/([A-Z]+)\//);
if(result){
$('#MyDiv').load('state-loader.html .state-' + result[1]);
}

Categories

Resources