How to reload JSON with AJAX every 10 Seconds - javascript

I'm trying to reload a JSON file every 10 seconds with JQUERY.
The page is here: http://moemonty.com/chirp/chirp.html
The Code is here:
<html>
<head>
<title>the title</title>
<!-- included Jquery Library -->
<script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
<!-- jquery library -->
</head>
<body>
<script>
$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new
function loadChirp(){ //start function
var url = "http://www.chirpradio.org/json";
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data){
console.log(data.query.results.json);
document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );
document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');
document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');
document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');
document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');
document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');
document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');
document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');
setTimeout("loadChirp()",5000);
alert('The timeout was triggered.');
});
} //end function
$(document).ready(function(){
//DOCUMENT READY FUNCTION
loadChirp();
});
//DOCUMENT READY FUNCTION
</script>
</body>
</html>
It doesn't seem to be working.

You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...

I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:
setTimeout(loadChirp, 5000);
...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).
But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.

You have an error in console.log(data.query.results.json); - console is not defined.
Also, you can use setInterval( "function()", 5000 );.

You should definitely use:
setInterval("loadChirp", 10000):
Don't write loadCrirp() inside setInterval as we're only passing a refrence

Related

Prepending constructed variable to HTML in JS

I started learning web developing for fun a couple weeks ago and I'm creating a rock-paper-scissors game using HTML, CSS and JS. I'm trying to add something to a block of HTML, but failing to do so with my current code. After a lot of googling I decided to try posting my question.
I added the function I'm trying to add the lines from and the place I'm trying to add them to. As I said, my code is not working and I don't quite understand why.
function displayPlayedRounds(winner) {
"use strict";
// <p class="roundCountPrev">
// <img src="/images/whiteRock.png" class="player1PrevRound"/>
// ← Round 4
// <img src="/images/blackPaper.png" class="player2PrevRound"/>
// </p>
var middlePart, toAppend;
if (winner === -1) {
middlePart = "Round " + movesMade + " →";
} else if (winner === 1) {
middlePart = "← Round " + movesMade;
} else {
middlePart = "Round " + movesMade;
}
toAppend = "<p class='roundCountPrev'><img src=" + userImages[userChoice] + " class='player1PrevRound'/>" + middlePart + "<img src=" + compImages[compMove] + "class='player2PrevRound'/></p>";
document.getElementById('displayPrevRounds').prepend('toAppend');
}
<span id='displayPrevRounds' class="player1">Previous rounds
<p class="roundCountPrev">
<img src="/images/whiteRock.png" class="player1PrevRound"/>← Round 4
<img src="/images/blackPaper.png" class="player2PrevRound"/>
</p>
</span>
firstly, as #madalin ivascu says, prepend is a jQuery function, not comes from DOM methods.
if you want use jQuery, it does a convenient way, you need "import/require/include" jQuery first. like:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
then, you can use this:
$('#displayPrevRounds').prepend(toAppend);
note that, no '', it's a var not chr.
if you want use DOM methods anyway, you can...
actually, i found you question via Google:"document html prepend",
use DOM Method:
parentNode.insertBefore(newChild, refChild);
How can I implement prepend and append with regular JavaScript?
and, here:
Append and Prepend without JQuery?
prepend is a jquery function, create a jquery object
$('#displayPrevRounds').prepend(toAppend);

Parsing json from external url Html and JS only

<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link="http://mywp.com/cilacap/api/get_posts/";
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id' ';
</script>
</html>
It only shows "hi".
Can someone tell me how to show JSON items such as "id" and "postDate"
with looping but without PHP scripting?
Thanks
Few syntactical errors, below is the right one.
<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link='{"url":"http://mywp.com/cilacap/api/get_posts/", "id":"url_id_01"}';
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id + ' ';
</script>
</html>
JSON Data(var link), was not parsable.
JSON Data(var link), didnt contained any attribute called id.
String concatenation in last line(output.innerHTML), was wrong.
Try removing the quotes from:
output.innerHTML=jcontent.id' ';
and change it to:
output.innerHTML += jcontent.id;
Providing that the link is valid it should work now.
You can also write:
console.log(jcontent);
and check if the console displays the value, or any errors that have occurred.
That url is a string, not json.
Use Ajax to get the data ( using jquery)
var link;
$.ajax({
url: "test.html",
}).done(function(data) {
link = data;
});
Then, extract the data;
output.innerHTML=jcontent.id;
Is for the value. You get the key like this:
ES7
Object.entries(jcontent)
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES6
Object.keys(jcontent)
.map(key => [key, jcontent[key]])
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES5 (Most likely your case)
Use function instead of arrow functions for es5:
Object.keys(jcontent)
.map(function(key){ [key, jcontent[key]] })
.forEach(function(keyValuePair)
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
Access the value:
keyValuePair[0] // key
keyValuePair[1] // value
Ps
If you want to use the es7 or es6 method, have a look at babeljs

Jquery/Ajax - Get Picture and Youtube in HTML

So i'm back here again trying to figure out how to use HTML correct and can't get it to work correctly after been trying many hours with this.
Anyways, i'm trying to make so the picture and youtube trailer should be shown in the HTML and what I search for is something like this.
Right now im searching to make something like the picture but to get picture to be shown and a player with the trailer
so basically I want it to look similar like picture number one and I have come so far:
<!DOCTYPE html>
<html>
<head>
<title>Movies</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function callAjax(input)
{
var url = "http://localhost:1337/search/" + input;
$.ajax({
type:'GET',
url: url,
success: function(data)
{
console.log('SUCCESS');
$('#title').html("Title: " + data.title);
$('#release').html("Release: " + data.release);
$('#vote').html("Vote: " + data.vote);
$('#overview').html("Overview: " + data.overview);
$('#poster').html("Poster: " + data.poster);
},
error: function(request, status, err)
{
console.log('ERROR');
}
});
}
$(document).ready(function(){
$('#get-json').on('click', function(e){
e.preventDefault();
var input = $('#data').val().trim();
callAjax(input);
});
});
</script>
<body>
<center>
<div>
<input type="text" id="data" name="data" size="15" maxlength="120" />
<button type="submit" value="search" id="get-json">Search</button>
</div>
</center>
<section>
<div id="json-output"></div>
<div id="title"></div>
<div id="release"></div>
<div id="vote"></div>
<div id="overview"></div>
<div id="poster" img src="data.poster" style="width:104px;height:142px;"></div>
</section>
</body>
</html>
Also forgot to say that i'm very new at this, never done HTML really before and been trying to figure out this for a while without a result :(
You need to create placeholders for your JSON elements. At first write without that JSON a sample of HTML page that will look like you want. That page should have elements (for example div) for title, release and so on. Those elements should have its class or ids to be addressed (as it is already with <div id="json-output">)
You do not have to stringify your JSON. It is better to work JSON, since you can address its elements. For example, to set value into specific placeholder element you can use:
$('#title').html(data.title);
$('#relese').html(data.release);
$('#vote').html(data.vote);
JSON.stringify will return the contents of a JSON object as a string. It will not parse your JSON object and return HTML.
You can create a simple list like this:
function(data){
var $list = $('<ul>');
$list.append('<li>Title: ' + data.title + '</li>');
$list.append('<li>Release: ' + data.release + '</li>');
$list.append('<li>Vote: ' + data.vote + '</li>');
$list.append('<li>Overview: ' + data.overview + '</li>');
$('#json-output').html($list);
}

Trouble inserting JavaScript var (containing stmt that contains markup) into <script>

I'm building a script dynamically (which is why it ends up in a var) but I've simplified this example. The problem I'm having is that the browser interprets the span tags inside the script as actual spans, rather than as part of the script. I've looked at all kinds of resources on escaping characters and html encoding/decoding, but either those aren't relevant issues or I'm just not getting it.
How can I write the span inside the dynamically-generated script so that the browser interprets it as part of the script and not as a span tag that it should render?
page.html file
<script>
$(document).ready(function () {
var formScript = ' $(document).on("ready", function () {';
formScript += $().BuildScript();
$("script#dynamic-script").append(formScript + '});');
});
</script>
<script id="dynamic-script"></script>
functions.js file
(function ($) {
$.fn.BuildScript = function () {
var stmtsToAdd = '';
stmtsToAdd += '$("#X").on("change", function () {' +
' if ($(this).val() == "1" && !$("#label-and-control_Y").is(":visible")) {' +
' $("#label-and-control_Y").show("fast");' +
' $("#control_Y").addClass("required");' +
' $("#control_Y").closest("div.control").prev().empty.append("<span class="required-field-indicator">");' +
' }' +
'});';
return stmtsToAdd;
}
})(jQuery);
variations
I have also tried using a variety of special characters, both with and without escaping backslashes (just in case I was misunderstanding something), with always the same result
"\u003cspan class=\\u0022required-field-indicator\\u0022\u003eRequired\u003c\/span\u003e"
"\x3cspan class=\x22required-field-indicator\x22\x3eRequired\x3c/span\x3e"
I also read that jQuery's html() was decoding, which is why I've tried append(), text(), and appendChild().
result

Javascript Help Passing Data via URL

Hi I wonder if someone could help me with this small issue I have the following code which I need to modify.
<script type="text/javascript">
function code(id) {
$('#myStyle').load('myphp.php?id=' + id);
}
</script>
I need to pass another variable into this code and add it to the GET part of the URL for example above it will include the URL myphp.php?id=124545
I want to add a second variable called num to the URL part but am confused what the code will need to become to make the correct post via GET
<script type="text/javascript">
function code(id,num) {
$('#myStyle').load('myphp.php?id=' + id); // how do I add the &num=124 for example
}
</script>
Thanks in advance
Simple. Use:
$('#myStyle').load('myphp.php?id=' + id + '&num=' + num);
Reference: http://www.quirksmode.org/js/strings.html#conc
Hope it helps!
Concatenate "&num="+num onto the string you already have:
<script type="text/javascript">
function code(id,num) {
$('#myStyle').load('myphp.php?id=' + id + "&num=" + num); // how do I add the &num=124 for example
}
</script>

Categories

Resources