Hello I am having this issue which I cant seem to figure out were I am getting the latest films from BBC and I am displaying them after that I am fetching each of the films titles and then using the movie db .org api to get the rating of the movie. But the problem here is when I am using the getJson function for the second time as it wont let me input the array as one of the json queries. Here is my code below:
$(function(){
var filmnamevar = [];
$.getJSON('http://www.bbc.co.uk/tv/programmes/formats/films/player/episodes.json?limit=3',function(data){
console.log('success');
$.each(data.episodes,function(i,emp){
$('#epis').append('<div class="episode-l">'+emp.programme+'<div id="epi-img"><img src="http://ichef.bbci.co.uk/images/ic/192x108/legacy/episode/'+emp.programme.pid+'.jpg"/></div> <div class="ep-title">'+emp.programme.title+'</div><div class="ep-title">'+emp.programme.short_synopsis+'</div></div>');
console.log(emp);
filmnamevar.push(emp.programme.title);
console.log(filmnamevar);
});
});
$.getJSON('http://api.themoviedb.org/3/search/movie?query='+filmnamevar[whichever number]+'&api_key=81c50c197b83129dd4fc387ca6c8c323&limit=1',function(data2){
$(data2.results,function(i,rat){
$('#epis').append('<div class="rating">'+rat.vote_average+'</div>');
});
});
});
You're appending the titles to an array (filmnamevar) but then you're accessing filmnamevar directly as if it were a string.
You'll need to loop the array, calling a new getJSON request for each title (unless the movie db API let's you pull many at once):
for( var i = 0; i < filmnamevar.length; i++){
$.getJSON('http://api.themoviedb.org/3/search/movie?query='+filmnamevar[i]+'&api_key=81c50c197b83129dd4fc387ca6c8c323&limit=1',function(data2){
$(data2.results,function(i,rat){
$('#epis').append('<div class="rating">'+rat.vote_average+'</div>');
});
});
}
Related
I am scraping websites using CasperJS and one of the tasks involve crawling across url set by a for loop counter. The url looks like this
www.example.com/page/no=
where the no is any number from 0-10 set by the for loop counter. The scraper then goes through all the pages, scrapes the data into a JSON object and repeats until no=10.
The data that I am trying to get is stored in discrete groups in each page- what I would like to work with is a single JSON object by joining all the scraped output from each page.
Imagine Page1 has Expense 1 and the object I am getting is { expense1 } and Page 2 has Expense 2 and object that I am getting is { expense2 }. What I would like to have is one JSON at the end of scraping that looks like this:
scrapedData = {
"expense1": expense1,
"expense2": expense2,
}
What I am having trouble is joining all the JSON object into one array.
I initialized an empty array and then each object gets pushed to array.
I have tried a check where if iterator i in for loop is equal to 10, then the JSON object is printed out but that didnt seem to work. I looked up and it seems Object spread is an option but I am not sure how to use it this case.
Any pointers would be helpful. Should I be using any of the array functions like map?
casper.then(function(){
var url = "https:example.net/secure/SaFinShow?url=";
//We create a for loop to go open the urls
for (i=0; i<11; i++){
this.thenOpen(url+ i, function(response){
expense_amount = this.fetchText("td[headers='amount']");
Date = this.fetchText("td[headers='Date']");
Location = this.fetchText("td[headers='zipcode']");
id = this.fetchText("td[headers='id']");
singleExpense = {
"Expense_Amount": expense_amount,
"Date": Date,
"Location": Location,
"id": id
};
if (i ===10){
expenseArray.push(JSON.stringify(singleExpense, null, 2))
this.echo(expenseArray);
}
});
};
});
Taking your example and expanding on it, you should be able to do something like:
// Initialize empty object to hold all of the expenses
var scrapedData = {};
casper.then(function(){
var url = "https:example.net/secure/SaFinShow?url=";
//We create a for loop to go open the urls
for (i=0; i<11; i++){
this.thenOpen(url+ i, function(response){
expense_amount = this.fetchText("td[headers='amount']");
Date = this.fetchText("td[headers='Date']");
Location = this.fetchText("td[headers='zipcode']");
id = this.fetchText("td[headers='id']");
singleExpense = {
"Expense_Amount": expense_amount,
"Date": Date,
"Location": Location,
"id": id
};
// As we loop over each of the expenses add them to the object containing all of them
scrapedData['expense'+i] = singleExpense;
});
};
});
After this runs the scrapedData variable should be of the form:
scrapedData = {
"expense1": expense1,
"expense2": expense2
}
Updated code
One problem with the above code is that inside the for loop when you loop over the expenses, the variables should be local. The variable names also should not be Date and Location since those are built-in names in JavaScript.
// Initialize empty object to hold all of the expenses
var scrapedData = {};
casper.then(function(){
var url = "https:example.net/secure/SaFinShow?url=";
//We create a for loop to go open the urls
for (i=0; i<11; i++){
this.thenOpen(url+ i, function(response){
// Create our local variables to store data for this particular
// expense data
var expense_amount = this.fetchText("td[headers='amount']");
// Don't use `Date` it is a JS built-in name
var date = this.fetchText("td[headers='Date']");
// Don't use `Location` it is a JS built-in name
var location = this.fetchText("td[headers='zipcode']");
var id = this.fetchText("td[headers='id']");
singleExpense = {
"Expense_Amount": expense_amount,
"Date": date,
"Location": location,
"id": id
};
// As we loop over each of the expenses add them to the object containing all of them
scrapedData['expense'+i] = singleExpense;
});
};
});
How does one delete an entire nested child from a Firebase database by referencing an entry to find the desired point of deletion?
For example, I have two entries nested under (list). (1) -KcxacywN4EkvwAzugfV and (2) -KcxaeBAIW-WgLAsajvV. I want to remove (2) -KcxaeBAIW-WgLAsajvV from the database using it's ID -KcxaeBAIW-WgLAsajvU-4-725391765511696 (See picture below).
I have a button setup for each database entry, to display a remove button. Each button, contains the data- or ID for each database entry.
rootRef.on("child_added", snap => {
var title = snap.child("title").val();
var link = snap.child("link").val();
var type = snap.child("type").val();
var id = snap.child("id").val();
$("#table_data").append("<div class='col-lg-4'><div class='card card-app'><div class='card-block'><h4 class='card-title'>"+ title +"</h4><small>"+ type +"</small><hr><a href='"+ link +"' target='_blank'>Download</a> <a class='user float-right' onclick='removeClick()' data-name='"+ id +"'>Remove</a> </div></div></div>");
});
The onClick event and associated id for the button, trigger this function. My mental idea, is to then take the ID from data- to delete its nested child, (2) -KcxaeBAIW-WgLAsajvV from the database. Same process for all other nested entries.
function removeClick() {
$(".user").click(function() {
rvm = $(this).attr("data-name");
});
alert(rvm);
firebaseRef.remove(rvm);
}
I've studied https://firebase.google.com/docs/database/web/read-and-write and can't seem to figure out the actual deletion of the nested entry. How can I use remove() or maybe another method to accomplish this?
I have been trying this, to get a better understanding.
firebaseRef.child(rvm).remove();
Since rootRef, is how I'm viewing data. I tried.
rootRef.child().remove();
This simply deletes the whole database...
Final running code:
function removeClick() {
$(".user").click(function() {
rvm = $(this).attr("data-name");
});
alert(rvm);
var query = rootRef.orderByChild("id").equalTo(rvm);
query.once("value", function(snapshot) {
snapshot.forEach(function(itemSnapshot) {
itemSnapshot.ref.remove();
});
});
}
You can only remove an item if you know its key. So given your current structure, you will first need to look up the key for the id you mention.
Assuming you have a variable ref that points to the root of the database:
var listRef = ref.child("list");
var query = listRef.orderByChild("id").equalTo("-KcxaeBAIW-WgLAsajvU-4-725391765511696");
query.once("value", function(snapshot) {
snapshot.forEach(function(itemSnapshot) {
itemSnapshot.ref.remove();
});
});
If you have only a single child with the id, you should consider restructuring your database to use the id as the key. If you do that, you could remove the item with:
listRef.child("-KcxaeBAIW-WgLAsajvU-4-725391765511696").remove()
I am trying to load my data from my JSON file but apparently only the first attribute was loaded. I created an array by using jQuery push method to extract the data from my JSON file. When I see the array output from console.log, it looks fine.
I don't get what went wrong
my html
<h2>My message list </h2>
{{#msg}}
<img src= {{icon}} >
{{subject}}
{{detail}}
{{date}}
{{/msg}}
my Script
<script type="text/javascript">
function loadUser1(){
var template = $('#template').html();
Mustache.parse(template); // optional, speeds up future uses
$.getJSON( "messages.json", function( data ) {
console.log('loaded');
var messageslist = []; // create array here
$.each(data.messages, function (index, message) {
messageslist.push("{icon:'"+message.icon+"',subject:'"+message.subject+",detail:'"+message.detail+"',date:'"+message.date+"'}"); //push values here
});
console.log(messageslist);//see output
var rendered = Mustache.render(template,{"msg":messageslist});
$('#target').html(rendered);
});
}
</script>
The array shows in the console: (I have repetitive dummy data in json)
Array [ "{icon:'images/alert_bad.png',subject:'Supply Chain - Past Due,detail:'Gerry Harrison',date:'01/16/2015'}", "{icon:'images/alert_bad.png',subject:'Supply Chain - Past Due,detail:'Gerry Harrison',date:'01/16/2015'}", "{icon:'images/alert_bad.png',subject:'Supply Chain - Past Due,detail:'Gerry Harrison',date:'01/16/2015'}" ]
You're creating object as JSON string instead of javascript object, try this:
var rendered = Mustache.render(template,{"msg": data.messages});
the data.messages is already correct not need to push to another array.
I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator
I have an AJAX request to bring me the values of coordinates from the server.
Heres my code:
locationsObj = []; //Somewhere above the AJAX request
//Below is from the success callback of the request
for (var i = 0; i < rowCount; i++) {
var storelatlng = new google.maps.LatLng(
parseFloat(result.storeLat[i]),
parseFloat(result.storeLon[i])
);
locationsObj.push(??);
}
What I want is to be able to store the returned values in an array OR JSON object, but Ive been fiddling around for ages and I cant seem to get it to work. I believe I may be storing them right, but can not get them out of the array/object as I am getting confused with the [i]'s and [0]'s.
Here is my attempt:
locationsObj.push({storelatlng: storelatlng});
As this is in the for loop, I assume it will loop through and add each var storelatlng to the object??? But how do I get the values back out?
this will give you an array of objects like this:
locationsObj = [
{ storelatlng: 'some value' },
{ storelatlng: 'some value' },
{ storelatlng: 'some value' }
];
so you would access it by:
locationsObj[i].storelatlng;