Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
<!DOCTYPE html>
<html>
<head>
<title>Local Weather</title>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.10/css/weather-icons-wind.css">
<link rel="stylesheet" type="text/css" href="Local Weather.css">
</head>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
</html>
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function()
{
$.getJSON("https://freegeoip.net/json/", function(data)
{
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
$.getJSON(url, function(data2)
{
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src='+ data2.weather[0].icon + '/>');
btn = $("#corf");
btn.click(function ()
{
if(test)
{
temp = (temp * 1.8) + 32;
$("#degree").html(temp + '<button id="corf">℉</button>');
test = false;
}
else
{
temp = (temp * 0.5556) - 32;
$("#degree").html(temp + '<button id="corf">℃</button>');
test = true;
}
});
});
});
});
Cannot change Celsius to Fahrenheit multiple times, what's wrong?
You are trying to bind the click event to the element which doesn't exists in the DOM. To make sure your events binding is proper you can use Event Delegation. Just add event to the parent element and check for the event.target. If event.target is the button, the do the proper calculation.
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function() {
$.getJSON("https://freegeoip.net/json/", function(data) {
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude;
$.getJSON(url, function(data2) {
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src=' + data2.weather[0].icon + '/>');
$('#degree').click(function(e) {
if (e.target.id === 'corf') {
var newTemp = 0;
if (test) {
newTemp = (temp * 1.8) + 32;
$("#degree").html(newTemp + '<button id="corf">℉</button>');
test = false;
} else {
newTemp = temp;
$("#degree").html(newTemp + '<button id="corf">℃</button>');
test = true;
}
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
Try this:
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function()
{
$.getJSON("https://freegeoip.net/json/", function(data)
{
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
$.getJSON(url, function(data2)
{
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src='+ data2.weather[0].icon + '/>');
btn = $("#corf");
$(document).on('click',btn,function ()
{
if(test)
{
temp = (temp * 1.8) + 32;
$("#degree").html(temp + '<button id="corf">℉</button>');
test = false;
}
else
{
temp = (temp - 32) / 1.8;
$("#degree").html(temp + '<button id="corf">℃</button>');
test = true;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
Related
I'm parsing JSON feed from the blogger API but its throwing following error:
37:59 Uncaught TypeError: Cannot read property 'url' of undefined
Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.
Javascript Code:
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/');
var postTimestamp = json.feed.entry[i].published.$t;
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= '+ postTimestamp +'>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
//document.write(item);
document.getElementById("news").appendChild(item);
console.log(item);
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
<div id="news"></div>
JsFiddle: https://jsfiddle.net/645pg9rz/
If you run console.log(json.feed.entry) in your fiddle, you'll see that there is no key called media$thumbnail in the returned objects. That is why your code is failing at var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/'); - it is trying to access the url property of an item that doesn't exist.
Perhaps the API used to use that key and no longer does, or there are just no thumbnails available in the entries you requested. I don't see a new key with an image file other than the Blogger logo.
Updated: the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)
there are no pictures in the object that came to you. It's the only icon that comes. I put them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="row" id="news"></div>
<script>
function mycallback(json) {
console.log(json)
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, 400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].author[0].gd$image.src;
var postTimestamp = json.feed.entry[i].published.$t;
console.log(postImage)
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= ' + postTimestamp + '>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
document.getElementById("news").innerHTML += item;
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
</body>
</html>
In my getValueByKey function, I want to output 5 different items and their attributes, but my for loop only seems to allow me to choose one at a time.
When I change to i = 4 it will go to the 5th item. I just want to output all instead of choosing just one.
Any help is appreciated. Thank you very much.
window.onload = function() {
var getJSON = function (url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', url, true);
xhr.setRequestHeader("X-Algolia-Application-Id", apiApplicationId);
xhr.setRequestHeader("X-Algolia-API-Key", apiKey);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
successHandler && successHandler(xhr.response);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
var search = document.getElementById('search');
search.addEventListener('keyup', function() {
getJSON(apiEndpoint, function(data) {
function getValueByKey(key, data) {
var i, len = data.length;
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
return data[i][key];
}
}
return -1;
}
document.getElementById('item-wrapper').innerHTML =
'<div class="col-sm-4">' +
'<img src="path/to-image.jpg">' +
'</div>' +
'<div class="col-sm-8">' +
'<ul>' +
'<li><strong>Bag Brand:</strong> <span id="search-results-brand"></span></li>' +
'<li><strong>Bag ID:</strong> <span id="search-results-id"></span></li>' +
'<li><strong>Bag Color:</strong> <span id="search-results-color"></span></li>' +
'<li><strong>Bag Description:</strong> <span id="search-results-description"></span></li>' +
'<li><strong>Bag Material:</strong> <span id="search-results-material"></span></li>' +
'<li><strong>Bag Price:</strong> $<span id="search-results-price"></span></li>' +
'</ul>' +
'</div>';
output_id = getValueByKey('id', data.hits);
output_brand = getValueByKey('brand', data.hits);
output_color = getValueByKey('color', data.hits);
output_description = getValueByKey('description', data.hits);
output_material = getValueByKey('material', data.hits);
output_price = getValueByKey('price', data.hits);
document.getElementById("search-results-brand").innerHTML = output_brand;
document.getElementById("search-results-id").innerHTML = output_id;
document.getElementById("search-results-color").innerHTML = output_color;
document.getElementById("search-results-description").innerHTML = output_description;
document.getElementById("search-results-material").innerHTML = output_material;
document.getElementById("search-results-price").innerHTML = output_price;
}, function(status) {
alert('Something went wrong.');
});
});
};
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/common.css">
<script type="application/ecmascript" src="js/common.js"></script>
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1>Test</h1>
</div>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-sm-12">
<input placeholder="search bags" id="search">
</div>
</div>
</div>
<div class="container">
<div class="row item-row" id="item-wrapper"></div>
</div>
</body>
</html>
You are return data[i][key]; . Do not return untill loop finishes.
function getValueByKey(key, data) {
var i, len = data.length;
var result =[];
for (i = 0; i < len; i++) {
if (data[i] && data[i].hasOwnProperty(key)) {
result.push(data[i][key]);
}
}
return result;
}
Edit for your question in the comment
As per my understanding your question, you can try something like this.I did not test this code. Let me know if there are any errors.
var items;
for(var i=0; i<output_id.length; i++){
items +='<div class="col-sm-4">' +
'<img src="path/to-image.jpg">' +
'</div>' +
'<div class="col-sm-8">' +
'<ul>' +
'<li><strong>Bag Brand:</strong>'+output_brand[i]+'<span id="search-results-brand"></span></li>' +
'<li><strong>Bag ID:</strong>'+output_id[i]+' <span id="search-results-id"></span></li>' +
'<li><strong>Bag Color:</strong>'+output_color[i]+' <span id="search-results-color"></span></li>' +
'<li><strong>Bag Description:</strong>'+output_description[i]+' <span id="search-results-description"></span></li>' +
'<li><strong>Bag Material:</strong>'+output_material[i]+' <span id="search-results-material"></span></li>' +
'<li><strong>Bag Price:</strong> '+output_price[i]+'$<span id="search-results-price"></span></li>' +
'</ul>' +
'</div>';
}
document.getElementById('item-wrapper').innerHTML =items;
I am using Node.js + Express + Jade + Socket.io to set up click events in one browser to trigger a click on a button in another. I am having difficulty getting this to work. The code I have so far is:
Client side (index.jade):
var socket = io.connect('http://localhost:8080');
$('#buttonLeft').tap(function() {
socket.emit('keyLeft');
});
});
Server side:
var sockets = {};
io.sockets.on('connection', function (socket) {
socket.on('keyLeft', function(){
socket.broadcast.emit('keyLeft');
});
});
Another client side (index.php):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="slider-style.css" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<?php
$imagesTotal = 8; // SET TOTAL IMAGES IN GALLERY
?>
<div class="galleryContainer">
<div class="galleryPreviewContainer">
<div class="galleryPreviewImage">
<?php
for ($i = 1; $i <= $imagesTotal; $i++) {
echo '<img class="previewImage' . $i . '" src="images/image' . $i . '.jpg" width="900" height="auto" alt="" />';
}
?>
</div>
<div class="galleryPreviewArrows">
<a id="previousSlideArrow" href="#" class="previousSlideArrow"><</a>
<a id="nextSlideArrow" href="#" class="nextSlideArrow">></a>
</div>
</div>
<script type="text/javascript">
// init variables
var imagesTotal = <?php echo $imagesTotal; ?>;
var currentImage = 1;
var thumbsTotalWidth = 0;
$('a.galleryBullet' + currentImage).addClass("active");
$('a.thumbnailsimage' + currentImage).addClass("active");
$('div.description' + currentImage).addClass("visible");
// PREVIOUS ARROW CODE
$('a.previousSlideArrow').click(function() {
$('img.previewImage' + currentImage).hide();
$('a.galleryBullet' + currentImage).removeClass("active");
$('a.thumbnailsimage' + currentImage).removeClass("active");
$('div.description' + currentImage).removeClass("visible");
currentImage--;
if (currentImage == 0) {
currentImage = imagesTotal;
}
$('a.galleryBullet' + currentImage).addClass("active");
$('a.thumbnailsimage' + currentImage).addClass("active");
$('img.previewImage' + currentImage).show();
$('div.description' + currentImage).addClass("visible");
return false;
});
// ===================
// NEXT ARROW CODE
$('a.nextSlideArrow').click(function() {
$('img.previewImage' + currentImage).hide();
$('a.galleryBullet' + currentImage).removeClass("active");
$('a.thumbnailsimage' + currentImage).removeClass("active");
$('div.description' + currentImage).removeClass("visible");
currentImage++;
if (currentImage == imagesTotal + 1) {
currentImage = 1;
}
$('a.galleryBullet' + currentImage).addClass("active");
$('a.thumbnailsimage' + currentImage).addClass("active");
$('img.previewImage' + currentImage).show();
$('div.description' + currentImage).addClass("visible");
return false;
});
// ===================
</script>
<script src="http://mojoer.kr:8080/socket.io/socket.io.js"></script>
<script src="slide-script.js></script>
</body>
</html>
Any help would be really appreciated. Thanks~
I tried to reproduce your setup with the following code:
server:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function (req, res) {
res.render('index');
});
io.on('connection', function (socket) {
socket.on('left', function () {
socket.broadcast.emit('leftButtonClicked');
});
socket.on('right', function () {
socket.broadcast.emit('rightButtonClicked');
});
});
http.listen(3000, function(){
console.log('listening on port 3000');
});
jade client:
doctype html
html
body
h1 Testing socket.io
h3(id="status") not connected
buttons
button#leftButton Prev
button#rightButton Next
br
h3 actions:
p#actions
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
});
document.getElementById("leftButton").addEventListener('click', function () {
socket.emit('left');
document.getElementById("actions").innerHTML += "Prev button click sent<br>";
});
document.getElementById("rightButton").addEventListener('click', function () {
socket.emit('right');
document.getElementById("actions").innerHTML += "Next button click sent<br>";
});
html gallery:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
</head>
<body>
<div>
<div id="preview" style="padding: 5px;"></div>
<div id="fullSize" class="fullgalleryPreviewImage" style="padding: 5px;"></div>
<div style="padding: 5px;">
<button id="previousSlideArrow" style="height: 4em; width=100px;"><</button>
<button id="nextSlideArrow" style="height: 4em; width=100px;">></button>
</div>
</div>
<script type="text/javascript">
// init variables
var imagesTotal = 8;
var currentImage = 1;
for (var i = 1; i <= imagesTotal; i++) {
document.getElementById('preview').innerHTML += '<img class="previewImage' + i + '"src="images/image' + i + '.jpg" + width="200" height="auto" style="margin-left: 2px;" />';
}
document.getElementById('fullSize').innerHTML = '<img src="images/image' + currentImage + '.jpg" + width="800" height="auto" />';
// PREVIOUS ARROW CODE
document.getElementById('previousSlideArrow').addEventListener('click', function () {
currentImage--;
if (currentImage === 0) {
currentImage = imagesTotal;
}
document.getElementById('fullSize').innerHTML = '<img src="images/image' + currentImage + '.jpg" + width="800" height="auto" />';
});
// NEXT ARROW CODE
document.getElementById('nextSlideArrow').addEventListener('click', function () {
currentImage++;
if (currentImage === imagesTotal + 1) {
currentImage = 1;
}
document.getElementById('fullSize').innerHTML = '<img src="images/image' + currentImage + '.jpg" + width="800" height="auto" />';
});
// socket.io
var socket = io("http://localhost:3000");
socket.on('connect', function () {
console.log('connected');
});
socket.on('leftButtonClicked', function () {
document.getElementById('previousSlideArrow').click();
});
socket.on('rightButtonClicked', function () {
document.getElementById('nextSlideArrow').click();
});
</script>
</body>
</html>
It works - when you click buttons in the jade client you can browse the gallery in the html client.
Please move the socket.io loader <script src="http://mojoer.kr:8080/socket.io/socket.io.js"></script> to the <head> section - if you have it at the end of the <body> it is not loaded yet when you execute var socket = io(<server address>); and you should see the error Uncaught ReferenceError: io is not defined in your browser's console.
I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.
I am trying to do a RSS reader chrome extension based on an example from lifehacker (http://lifehacker.com/5857721/how-to-build-a-chrome-extension). I did my own based on that. It didn't work. I tried their source code and it worked perfectly fine(for lifehacker), but when I changed the xml source as http://www.engadget.com/rss.xml it only showed an empty square.If anyone can point any mistake or error, I would be truly thankful.My files are :
manifest.json
{
"name": "RSS Fetcher",
"version": "0.1",
"description": "engadget rss reader.",
"homepage_url": "http://www.engadget.com/",
"background_page": "background.html",
"permissions": [
"<all_urls>",
"http://www.engadget.com/*"
],
"browser_action": {
"default_title": "engadget reader",
"default_popup": "popup.html"
}
}
background.html
<html>
<head>
<script src='scripts/jquery-1.6.1.min.js'></script>
<script src="scripts/parse.js"></script>
<script>
function fetch_feed(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
callback(data);
} else {
callback(null);
}
}
}
// Note that any URL fetched here must be matched by a permission in
// the manifest.json file!
xhr.open('GET', url, true);
xhr.send();
}
function onRequest(request, sender, callback) {
if (request.action == 'fetch_feed') {
fetch_feed(request.url, callback);
}
}
// Wire up the listener.
chrome.extension.onRequest.addListener(onRequest);
</script>
</head>
<body>
</body>
</html>
popup.html
<html>
<head>
<script src='scripts/jquery-1.6.1.min.js'></script>
<script src="scripts/parse.js"></script>
<script>
function fetch_feed() {
chrome.extension.sendRequest({'action' : 'fetch_feed', 'url' : 'http://www.engadget.com/rss.xml'},
function(response) {
display_stories(response);
}
);
}
function display_stories(feed_data) {
var xml_doc = $.parseXML(feed_data);
$xml = $(xml_doc);
var items = $xml.find("item");
$('#popup').html('<img src="images/logo.png" id="logo" onclick="open_item(\'http://engadget.com/\'); window.close();" /><br clear="all" />');
items.each(function(index, element) {
var post = parse_post(element);
var item = '';
var class2 = '';
if (index >= localStorage['unread_count']) {
// // console.log('visited');
item += '<div class="post read">';
}
else {
item += '<div class="post">'
}
item += '<span class="tag">' + post.tag + '</span>\
<a href="' + post.url + '">\
<div id="' + post.id + '" class="item" onclick="open_item(\'' + post.url + '\');">\
<img src="' + post.img + '" width="107" height="60" />\
<h4>' + post.title + '</h4>\
<span class="description">' + post.description + '...</span>\
</div>\
</a>';
item += '</div>';
$('#popup').append(item);
});
}
</script>
<link rel="stylesheet" href="styles/post.css" type="text/css" />
</head>
<body>
<div id="popup">
</div>
<script>
$(document).ready(function() {
fetch_feed();
});
</script>
</body>
</html>
parse.js
function parse_post(element) {
// console.log(element);
var post = new Object();
post.title = $(element).find("title").text();
post.tag = post.title.split('[')[1].split(']')[0];
post.title = post.title.split('[')[0];
post.id = $(element).find("guid").text();
post.url = $(element).find('link').text();
post.description = $("<div/>").html($(element).find("description")).text();
post.img = $('img', post.description)[0].src; //107x60px
var shorten = 120;
if (post.title.length > 80) {
shorten = 70;
}
post.description = $.trim($(post.description).text());
post.description = post.description.substr(0, shorten);
// console.log(post);
return post;
}
function open_item(url) {
chrome.tabs.create({url: url});
chrome.browserAction.setBadgeText({text:''});
}
I also used jquery-1.6.1.min.js
Anything helps:) Thanks in advance!
not sure "all_urls" works in your manifest.json, remove that and give it a try