Pull RSS feed using Jquery .get; cross domain issues? - javascript

I have been trying to get the example from How to parse an RSS feed using JavaScript? working. My HTMl/script is below. The get request isn't working. I'm not getting any errors, just nothing happening.
Is this because of cross-domain issues? Can anyone spot the issue? Ultimately, I want to pull treasury prices from government rss feeds such as:
http://www.federalreserve.gov/feeds/Data/H15_H15_RIFSGFSW04_N.B.XML
Am I taking the right approach?
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.11.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
$(document).ready(function() {
alert('Jquery working fine');
$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
});
</script>
</head>
<body>
</body>

Related

How to display rest api using AJAX in Django?

I want to be able to use the REST API below and display data on a single HTML page.
This is the API (response) from a database connection function in my Django project.
URL: http://127.0.0.1:8000/api/v1/test/
API output:
{
"message": "Success !",
"server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)"
}
I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>API Calls Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid">
<h3>Test Output</h3>
<br></br>
<table class="table table-sm">
<tr>
<th>Output</th>
</tr>
<tbody id="divBody"></tbody>
</table>
</div>
</body>
<script>
$(document).ready(function () {
BindConnection();
});
function BindConnection(){
$.ajax({
type:"GET",
dataType: "JSON",
url: "http://127.0.0.1:8000/api/v1/test",
success: function(data){
console.log(data);
var str = "";
var totalLength = data.length;
for (let i=0; i < totalLength; i++){
str += "<tr>" +
"<td>" + data[i].server + "</td>"
"</tr>"
}
$("#divBody").append(str)
}
});
}
</script>
Note: The result can be displayed on the console and there is no error.
Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts but I cannot make it.
Could you please help me to answer this problem? Thank you!
i think the following line who causing the problem
var totalLength = data.length;
it seems the dictionary has no attribute length as the api response with dictionary so you need to deal with it as a dictionary not array
if you tried to add line
console.log(totalLength)
it will be undifiend value so no looping happening

How to Use the JSON file in my HTML web page

I am trying to implement the following JSON file in my HTML page.
<html>
<head>
<title> test get</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script>
$(function() {
$.getJSON('json.json',function(data) {
$.each(data.quotes,function(key,value) {
alert( key+ "said by "+value);
});
});
});
</script>
</head>
<body>
</body>
</html>
Here is the JSON that i am working on.
{
"quotes": {
"hey there":"randomguy1",
"wassup":"randomguy2",
"coool":"randomguy3"
}
}
I have checked different tutorials and similar questions at stackoverflow still couldn't figure out the mistake.
Just fix your script code,
You MUST close the <script ...jquery> tag.
<html>
<head>
<title>test get</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function () {
$.getJSON('json.json', function (data)
{
$.each(data.quotes, function (key, value) {
alert(key + "said by " + value);
});
});
});
</script>
</head>
<body> </body>
</html>
You can achieve it in a different manner. Use ajax to load a file content and parse it as a json.
$.ajax({
url : "helloworld.json",
success : function (data) {
//TODO parse string to json
}
});

Youtube Data Api - Uncaught TypeError: Cannot read property 'setApiKey' of undefined

I search music with youtube data api. I use javascript and jquery and i have a problem.
Here is my code
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="<?php echo SITE_PUBLIC; ?>/bootstrap-3.2.0/dist/js/bootstrap.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
function keyWordsearch(){
gapi.client.setApiKey('myapikey');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"},{"name":"shakira"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
</script>
This code not working. Chrome console say "Uncaught TypeError: Cannot read property 'setApiKey' of undefined". But this code is working:
keyWordsearch() to
$(document).click(function(){
keyWordsearch()
})
I do not understand this issue. Thanks in advance
EDIT
My code run on jsFiddle.But not run my html file. My html file is here:
<!doctype html>
<html>
<head>
<title>Search</title>
</head>
<body>
<div id="container">
<h1>Search Results</h1>
<ul id="results"></ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
<script>
$(function(){
function keyWordsearch(){
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"eminem"}] }' );
$.each(data["data"], function( index, value ) {
makeRequest(value["name"]);
});
});
}
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 10
});
request.execute(function(response) {
$('#results').empty()
var srchItems = response.result.items;
$.each(srchItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
})
})
}
keyWordsearch();
})
</script>
</body>
</html>
Looks like, you haven't load the javascript library. That's why it can't find the reference.
You can add it like:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
You can specify an initial function while calling the API like this: client.js?onload=init (see my example below). Besides no need of a doucument.ready() wrapper. I'm not sure why it works with your API key on my local machine but I guess it's some kind of magic that checks if the site is availible to the public - if true the referrer entries in your google account will get important - correct me on that if somebody knows whats exactly happening here.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<!--<link rel="stylesheet" type="text/css" media="screen" href="main.css" />-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script type="text/javascript">
function makeRequest(q) {
var request = gapi.client.youtube.search.list({
q: q,
part: 'snippet',
maxResults: 3
});
request.execute(function(response) {
$('#results').empty();
var resultItems = response.result.items;
$.each(resultItems, function(index, item) {
vidTitle = item.snippet.title;
vidThumburl = item.snippet.thumbnails.default.url;
vidThumbimg = '<pre><img id="thumb" src="'+vidThumburl+'" alt="No Image Available." style="width:204px;height:128px"></pre>';
$('#results').append('<pre>' + vidTitle + vidThumbimg + '</pre>');
});
});
}
function init() {
gapi.client.setApiKey('AIzaSyCWzGO9Vo1eYOW4R4ooPdoFLmNk6zkc0Jw');
gapi.client.load('youtube', 'v3', function() {
data = jQuery.parseJSON( '{ "data": [{"name":"orsons"}] }' );
$.each(data["data"], function(index, value) {
makeRequest(value["name"]);
});
});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=init"></script>
</head>
<body>
<h1>YouTube API 3.0 Test</h1>
<ul id="results"></ul>
</body>
</html>
In addition to all the answers which explain that you must specify and provide a callback function for the Google API client <script> loading line, I'd like to point out that it seems that the onload parameter will never run the specified function (at least in Chrome) when you load the Google API client.js from a local file (even though you are serving the HTML page via a webserver and not loading it from the file-system, which apparently seemed to be the only gotcha with the Google API JS client...).
e.g.:
<script src="/lib/js/client.js?onload=handleClientLoad"></script>
Although client.js will be loaded, this will never launch the handleClientLoad function when it's finished loading. I thought it would be useful to point this out, as this was a really frustrating thing to debug.
Hope this helps.
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
This MUST be called at the end, or at least after you define your method "handleClientLoad". This is its callback, and only after it was called - it means google api is ready. This is why you get gapi.client is null.
For the fun of it, you can use a timeout of a few seconds before using gapi.client and see it is not null anymore.

jQuery $.getJSON() not returning anything

I have a script that i'm using to experiment a bit with jQuery since i just started learning.
the script is supposed to read a .json file and display some data in a div.
function jQuerytest()
{
$.getJSON( "books/testbook/pageIndex.json", function(result) {
$.each(result, function(i, field) {
$("div").append("<p>" + field + "</p>");
});
});
}
here is the html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="styles/main.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="scripts/book.js"></script>
<script>jQuerytest();</script>
</head>
<body>
<div></div>
<figure id=fig><img onClick="jQuerytest()" src="figures/test620x620.png"/>
</figure>
</body>
</html>
but it doens't display anything.
If your JSON File is valid (You can test here: http://jsonlint.com/)
Use the success and error callback to finally get information why it's not working.
function jQuerytest(){
$
.getJSON( "books/testbook/pageIndex.json")
.success(function(result) {
$.each(result, function(i, field) {
$("div")
.append("<p>" + field + "</p>");
});
})
.error(function(error){
console.log(error);
});
}

Simple way of displaying images from parse.com database using javascript

I was working on a very simple page which just pulls and displays images from a table in parse.com. I do not have much experience with javascript which might be evident from the code below.
I need the images to show up in a chronological order. With the current code, it works fine most of the times but is a little buggy.
There are 2 main problems:
1) Sometimes, randomly, one particular new image might not come on the top and instead show up somewhere in between.
2) This page works on Firefox and Chrome but NOT on IE.
Is there a better way to implement this or is there something that I should change? Any help would be appreciated.
Page source-
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js"></script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url;
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});
</script>
</body>
</html>
Internet Explorer blocks mixed content. Since Parse's JavaScript SDK requires SSL, you need to host your app using HTTPS as well in order to access it from IE.
Hey you made one mistake. it was not working for me. Then i found that it is url() not url.
The amendment is img.src = results[i].get("image").url();
<!doctype html>
<head>
<meta charset="utf-8">
<title>My parse images</title>
<meta name="description" content="My Parse App">
<meta name="viewport" content="width=device-width">
<!-- <link rel="stylesheet" href="css/reset.css"> -->
<link rel="stylesheet" href="css/styles.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.0.min.js">
</script>
</head>
<body>
<div id="main">
<script type="text/javascript">
Parse.initialize("xxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx");
var config = {
parseAppId: 'xxxxxxxxxxxxxxxxxxx',
parseRestKey: 'xxxxxxxxxxxxxxxxxx',
streamName: 'parse-demo'
};
var getPhotos = function() {
var userImages = Parse.Object.extend("userImages");
var query = new Parse.Query(userImages);
query.find({
success: function(results) {
$('#photo-container').children().remove();
for(var i=results.length - 1; i>=0; i--){
var img = new Image();
img.src = results[i].get("image").url();
img.className = "photo";
document.body.appendChild( img );
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
};
function refresh (timeoutPeriod){
refresh = setTimeout(function(){window.location.reload(true);},timeoutPeriod);
}
$(document).ready(function() {
getPhotos();
// refresh(10000);
});

Categories

Resources