Grabbing Values from a JSON API Responce, putting them into webpage - javascript

Today I have a question that may seem kinda simple the the rest of you. I'm just now learning how to use APIs/JSONs and I'm a little confused. I'm trying to simply grab the temperature from this openweathermap.org API response and displaying it in an html tag.
The javascript from what I know is grabbing the temperature and setting it as a var. I'm confused why I cannot use id="" to set text inside a tag. The code below is what I have so far. I thank you for your time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var weather;
var temp;
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather){
var temp = weather.main.temp;
}
});
</script>
</head>
<body>
<p id="temp"></p>
</body>
</html>

#ArunPJohny have already identified the errors: 1) missing }) and 2) use $('#temp') to get the HTML element. Also you don't need to declare weather because it is declared as an argument.
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather) {
$('#temp').text(weather.main.temp);
}
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<p id="temp"></p>

Related

How can I include the content of PHP files in output generated by JavaScript?

I have a JS script that scrapes a bit of data and outputs the result to the screen. That works fine. What I now need to do is wrap that output in some pre and post content php files for formatting purposes, and I can't seem to get it to work.
Here's where the script stands now:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<img id="loading-gif">
<script>
$('#loading-gif').hide();
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({
url: "https://aajumpseat.com/dev/include/pre.content.php'); ?>",
type: 'GET',
dataType:"json",
success: function(data) {
pre = JSON.parse(data);
document.write(pre);
}
});
$.ajax({url: "https://aajumpseat.com/dev/scrape/getSegments.php"}).done(function (data) {
$('#loading-gif').hide();
output = JSON.parse(data);
document.write(output);
});
$.ajax({
url: "https://aajumpseat.com/dev/include/post.content.php'); ?>",
type: 'GET',
dataType:"json",
success: function(data) {
post = JSON.parse(data);
document.write(post);
}
});
});
</script>
</body>
</html>
The second ajax call works perfectly and outputs the result to the screen, which is what I want. What I would like to do is place the contents of pre.content.php before the result and the contents of post.content.php after the result so that the result is properly formatted.
There is some php being executed in 'pre.content.php is addition to the formatting html, while 'post.content.php contains only the closing body and html tags.
If need be, I can hardcode the required html into the above script, but if someone has an elegant, or not so elegant, solution on how to include these two files I'd appreciate it.
Thanks.
There's a function specifically for this called $.load(). It's always better to have a <div> with id and then use .innerHTML instead of using document.write().
$(function () {
$("#stuff").load("/path/to/api/call");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stuff"></div>
If you have got multiple calls, that's fine too. Just have multiple containers.
$(function () {
$("#stuff").load("/path/to/api/call");
$("#pre").load("/path/to/api/code");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stuff"></div>
<pre id="code"></pre>
One thing to note is that, $.load() fires an AJAX GET request.
place the contents of pre.content.php before the result and the contents of post.content.php
Don't use document.write. It gives you no control over where in the document you write anything. Instead, define the elements where you want to write your output:
<div id="pre-output"></div>
<div id="main-output"></div>
<div id="post-output"></div>
Then write your output to those specific locations:
pre = JSON.parse(data);
$('#pre-output').html(pre);
(Or maybe .text(pre)? It's strange to me that you're outputting raw JSON...)
******* SOLUTION *******
My main php has multiple tasks, so for this particular task the PHP is:
$output = " <div id='loading-gif'><img src='images/loading3.gif';></div>
<div id='main-output'></div>
<script>
$('#loading-gif').hide();
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({url: 'https://aajumpseat.com/dev/scrape/getSegments.php'}).done(function (data) {
$('#loading-gif').hide();
output = JSON.parse(data);
//document.write(output);
$('#main-output').html(output);
});
});
</script>
<div class='bottom-border'></div>
";
and further down the page I have:
include('include/pre.content.php');
echo $output;
include('include/post.content.php');
And it is perfect.

Calling json data from an api

I am trying to retrieve data from an api and use it to populate the div with the ID "output". I get an error that the $ is undefined. Can anyone help determine what I am missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
</head>
<body style="margin: 0px; padding: 0px;">
<div id="fullscreen">
<div id="output">
</div>
</div>
</body>
<script>
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
</script>
</html>
As Sirko already explained in the comments, you are trying to use the javascript library JQuery, but the library is not available because you didn't include it.
You can include it by either downloading JQuery here and including it via
<script src="src_to_local_jquery.js"/>
or by including it externally (described in CDN section of above link)
Also note, that script tags should be put either in the head or the body section. To make sure your custom script is executed after the page is ready, you can use JQuery's document ready method.
The $ sign is not part of the JavaScript language, it is a short hand for a third party library jQuery ($ === jQuery).
You need to add it as a dependency in your html file with a script tag with a src attribute containing the URI for the source file before you can use it.
<html>
<head></head>
<body>
...
...
<script src="//code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(function () {
// Your code here
});
</script>
</body>
</html>
Include jQuery either as a CDN or download add reference locally. Then make sure the DOM is ready before you make the call. You can read more about that here
<script src="local_jquery.js"/>
// OR
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
$(function() {
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});

I have to get data from the following url which contains the data in json format

http://te.chni.ca/twitter.api/tweet.php
I tried all tutorials but unable to get the data from that please help me
try to get atleast one attribute so i can try the remaining ones
<!DOCTYPE html>
<html>
<head>
<title>Twitter</title>
</head>
<body>
<button id="initquery">Search</button>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(function(){
$('#initquery').click(function(){
$.getJSON('http://te.chni.ca/twitter.api/tweet.php',function(data){
var item=[];
$.each(data,function(key,val){
items.push('<li id="'+key+'">'+val+'</li>');
});
$('<ul/>',{
'class':'interests-list',
html:items.join('')
}).appendTo('body');
});
});
});
</script>
</body>
</html>
You need to be using jsonp. Do you see the parenthesis around the response from that API? That is tell-tale sign that this is intended to be jsonp.
You should use ajax() method for this:
$ajax(
url: 'http://te.chni.ca/twitter.api/tweet.php',
dataType: 'jsonp',
success: function(data) {
// your success function
}
);

Execute code if page doesn't load

I want to create a code that reloads a part of the page every 10 seconds and if it fails to reload (because of connection issue), then it plays a sound.
Is such thing possible using ajax and how? I have seen this type of feature in web chats before but never came across a code for it.
Try using setInterval function:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>Test</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/css">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript" language="JavaScript"></script>
<style type="text/css">
<!--
.square {
background-color: #AAAAAA;
width: 250px;
height: 100px;
}
//-->
</style>
<script type="text/javascript" language="JavaScript">
$(document).on('ready',function(){
setInterval(updateDiv,10000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
//Code to play a sound
$('.square').html('<span style="color:red">Connection problems</span>');
}
});
}
</script>
</head>
<body>
<h1>The next div will be updated every 10 seconds</h1>
<div class="square">
Hello
</div>
</body>
</html>
And the php script:
<?php
echo "Updated value --> " . rand();
?>
To test, try renaming the php script (simulating connection problems) and rename to original name (getContent.php) to test correct situation again. Hope this helps.
Using JQuery, you can add handlers to run on fail...
$.ajax({
dataType: "json",
url: "myurl.com"
}).done(function( data ) {
//do what you want when it's all good
}).fail(function() {
//do what you want when the call fails
});
Or you can do it this way...
$.ajax({
type: "post",
url: "/SomeController/SomeAction",
success: function (data, text) {
//do what you want when it's all good
},
error: function (request, status, error) {
//do what you want when the call fails
}
});
And per request, here is a jsfiddle, it calls a service every 2 seconds, either with a URL that will return the date, or with a bad URL that will fail, mimicking a failed server.
UPDATE: I modified the jsfiddle to play a sound, as long as that sound remains on the server it's on :)

Trying to remove duplicate info received from an xml file displayed on my html page

I am trying to delete the duplicate atrists that are displayed when I retrieve the info from this xml file using JQuery. How can I accomplish this?
Here is the js file:
$(function(){
$(window).load(function(){
$.ajax({
url: 'http://imaginationeverywhere.info/djronlove/new_2.xml',
dataType: 'xml',
success: function(xml){
$(xml).find("key:contains('Artist') + string").each(function(){
var string1 = $(this).text();
$('<p></p>').addClass('string1').html(string1).appendTo('#container');
});
}
});
});
$('<div></div>').attr('id', 'container').appendTo('body');
});
Here is the html file:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DJ Ron Love Music Catalog</title>
<script type='text/javascript' src='http://imaginationeverywhere.info/jslib//dev/jquery-1.5.1.js'>
</script>
<script type='text/javascript' src="http://imaginationeverywhere.info/djronlove/itunes.js">
</script>
</head>
<body>
<!--<h3>Songs that currently in DJ Ron Love's Music Catalog</h3>-->
<h3>Artist that DJ Ron Love currently has in roatation</h3>
</body>
</html>
one way you may want to try is by creating a master artist array, and then querying that before adding new artists. You can do this easily using jquerys "inArray" function.
var masterArray = new Array();
$.ajax({
url: 'http://imaginationeverywhere.info/djronlove/new_2.xml',
dataType: 'xml',
success: function(xml){
$(xml).find("key:contains('Artist') + string").each(function(){
var string1 = $(this).text();
if( jQuery.inArray(string1, masterArray) == -1 ){
$('<p></p>').addClass('string1').html(string1).appendTo('#container');
masterArray.push(string1);
}
});
}
});
Note: there may be more efficent ways to do this, but if you're just looking for something simple, that may work.

Categories