jQuery - put html in array for ajax query - javascript

I am trying to put some HTML in an array for an ajax query, but when I see array in console then there is only first line of the html. why ? is there a proper way to do this?
My code
var data = new Array();
$('.get_html').each(function() {
var html = $(this).html();
data.push(html);
});
console.log(data);

You're logging the variable content instead of the data array you're pushing html too.
console.log(data);

Change variable content to data in console.log
var data = new Array();
$('.get_html').each(function() {
var html = $(this).html();
data.push(html);
});
console.log(data);
JSFIDDLE

You need to use data instead of content, Also you can use .map() to do this
var data = $('.get_html').map(function () {
return $(this).html();//return this.innerHTML
}).get();
console.log(data);
Demo: Fiddle

Related

how can i filtering data from Firebase rt-db using javascript

I need to print in console value of key temp but no things displayed
var database=firebase.database();
var ratingRef = firebase.database().ref("sensors/temp/");
ratingRef.orderByValue().on("value", function(data) {
data.forEach(function(data) {
console.log( data.val());
});
});
There's no need for using orderByValue. You have direct reference to the temp child so the data (which is a DataSnapshot) contain the value of temp only.
var ratingRef = firebase.database().ref("sensors/temp");
ratingRef.on("value", function(data) {
console.log(`Temp: ${data.val()}`)
});

How do I use the DOM in JS to insert HTML headers for returning JSON files?

Hey guys I have a script that connects to a webservice that looks up artists and returns songs using JSON data.
I know how to use appendChild etc to return static text in a vacuum but I have a foreach loop that returns all the results from a database, within which I have to use the DOM to insert things like "Artist:" before the JSON variable.
JSfiddle: https://jsfiddle.net/21txhmr6/
function init() {
document.getElementById("submit").addEventListener("click", sendAjax);
}
function sendAjax() {
var a = document.getElementById('artist').value;
var ajaxConnection = new XMLHttpRequest();
var newDiv = document.createElement("P");
var newArtist = document.createTextNode("Artist:");
var newSong = document.createTextNode("Song:");
var newDownloads = document.createTextNode("Downloads:");
newDiv.appendChild(newArtist);
document.body.appendChild(newArtist);
ajaxConnection.addEventListener ("load", e => {
var output = "";
var artistList = JSON.parse(e.target.responseText);
artistList.forEach( curArtist => {
output = output + `${newArtist} ${curArtist.artist}</td> <td>Title: ${curArtist.title}</td> <td>Downloads: ${curArtist.downloads}</td></table>`
});
document.getElementById('jsonload').innerHTML = output;
});
// Open the connection to a given remote URL.
ajaxConnection.open("GET", `https://edward2.solent.ac.uk/~aelsbury/wadwebsite/htwebservice.php?artist=${a}`);
// Send the request.
ajaxConnection.send();
}
The main problem in your code seems to be the fact, that you create an invalid HTML structure in your loop. Each entry in the list should create a complete table row, I suppose, so just do that:
output = output + `<tr><td>${newArtist} ${curArtist.artist}</td> <td>Title: ${curArtist.title}</td> <td>Downloads: ${curArtist.downloads}</td></tr>`
and place the <table> tags around the complete output, for example in the assignment to innerHTML:
document.getElementById('jsonload').innerHTML = `<table>${output}</table>`;
It would be even better to not create HTML code, but DOM elements. This results in longer code, but makes sure that the structure is correct. You already do so for your newDiv element, just do it for the table rows and columns as well and you would not get such problems.

return array variable from csv - javascript / Node

So I'm running this code from a node console and I need to put the result as a variable
var csv = require('csv-array');
csv.parseCSV("my.csv"
, function(data){
console.log(JSON.stringify(data));
});
The array prints out fine, but how do I set the result as a variable? (I'm hoping this is as easy as it seems for someone with experience)
Here you go,
var csv = require('csv-array');
//variable declaration
var myVariable;
csv.parseCSV("my.csv", function(data){
myVariable = JSON.stringify(data);
return data;
});
//take it as a variable here.
console.log(myVariable);

Use JSON output from Flickr to display images from search

I need to display the images on my site from a JSON request.
I have the JSON:
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1
And I have the format I need to put the photo URL in:
https://www.flickr.com/services/api/misc.urls.html
But I don't know how I would loop through that, I found some examples similar, but I am still having trouble seeing what I need.
I am using JavaScript/jQuery to pull the info.
I figure I would have this in a loop.
CurrentPhotoUrl = 'https://farm'+CurrentPhotoFarm+'.staticflickr.com/'+CurrentPhotoServer+'/'+CurrentPhotoId+'_'+CurrentPhotoSecret+'_n.jpg'
But each of those variables would need to be populated with an value from the element. I would need to loop through all 5 elements that are in the JSON.
Any help on how to create this loop would be greatly appreciated.
Try this code
var n = JSON.parse(x) //x is the json returned from the url.
var _s = n.photos.photo;
for(var z = 0 ; z < n.photos.photo.length ; z++)
{
var CurrentPhotoUrl = 'https://farm'+_s[z]['farm']+'.staticflickr.com/'+_s[z]['server']+'/'+_s[z]['id']+'_'+_s[z]['secret']+'_n.jpg'
console.log(CurrentPhotoUrl);
}
Edit ( With actual JQUERY AJAX call )
var n ='';
$.ajax({url: "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1", success: function(result){
console.log(result);
n = result;
var _s = n.photos.photo;
for(var z = 0 ; z < n.photos.photo.length ; z++)
{
var CurrentPhotoUrl = 'https://farm'+_s[z]['farm']+'.staticflickr.com/'+_s[z]['server']+'/'+_s[z]['id']+'_'+_s[z]['secret']+'_n.jpg'
console.log(CurrentPhotoUrl);
}
}});
Output:
https://farm8.staticflickr.com/7198/6847644027_ed69abc879_n.jpg
https://farm3.staticflickr.com/2517/3905485164_84cb437a29_n.jpg
https://farm1.staticflickr.com/292/32625991395_58d1f16cea_n.jpg
https://farm9.staticflickr.com/8181/7909857670_a64e1dd2b2_n.jpg
https://farm9.staticflickr.com/8143/7682898986_ec78701508_n.jpg
This answer assumes your json data will not change. So inside a .js file, set your json to a variable.
var json = <paste json here>;
// the photos are inside an array, so use forEach to iterate through them
json.photos.photo.forEach((photoObj) => {
// the photo will render via an img dom node
var img = document.createElement('img');
var farmId = photoObj.farm;
// you can fill out the rest of the variables ${} in the url
// using the farm-id as an example
img.src = `https://farm${farmId}.staticflickr.com/${serverId}/${id}_${secret}.jpg`
// add the image to the dom
document.body.appendChild(img);
}
Inside your html file that contains a basic html template, load this javascript file via a script tag, or just paste it inside a script tag.
If you want to get the json from the web page and assuming you have the jquery script loaded...
$.ajax({
type: 'GET',
url: <flicker_url_for_json>,
success: (response) => {
// iterate through json here
},
error: (error) => {
console.log(error);
}
});
I'm not sure if this is the best solution but its is something someone suggested and it worked.
const requestURL = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=6a970fbb976a06193676f88ef2722cc8&text=sampletext&sort=relevance&privacy_filter=1&safe_search=1&per_page=5&page=1&format=json&nojsoncallback=1'
$.ajax(requestURL)
.done(function (data) {
data.photos.photo.forEach(function (currentPhoto) {
console.log('https://farm'+currentPhoto.farm+'.staticflickr.com/'+currentPhoto.server+'/'+currentPhoto.id+'_'+currentPhoto.secret+'_n.jpg')
})
})
Varun's solution worked for me as well. I don't know which one is better but I thought I would post this as well since it looks like they were done fairly differently.

getting json data from tree and feeding through to associative array

I'm trying to read a JSON API and parse the data into an associative array but I can't seem to get it to work. I must be doing something wrong.
Here is my code:
var matchedValues = {};
$.getJSON(url ,function(data) {
$.each(data, function() {
var value = this["value"];
var climb = this["climb"];
matchedValues[value] = climb;
});
});
console.log(matchedValues); //Outputs Object{}
Any ideas? I don't think I am console logging it correctly or maybe I'm doing something wrong?
Thanks
matchedValues is an Object not an array. try something likmatchedValues['your_key'] to get the value.
I assume that the data coming back from the ajax call is a JSON string, which you wish to parse. If that’s the case, then the problem is already solved using JavaScript’s JSON object:
var matchedValues = {};
$.getJSON(url ,function(data) {
matchedValues=JSON.parse(data);
});
console.log(JSON.stringfy(matchedValues)); //Outputs Object{}
As you see in the above example, you have to reverse the process in order to print it out.
See JSON MDN Article
Try this approach from jquery documentation
EDIT:
$.getJSON(url, function(data) {
var matchedValues = {};
$.each(data, function(key, val) {
items[key] = val;
});
If I understood your question, then your data is an Array of objects, and you want to consolidate them in a big object.
If got it right, then use this approach:
var matchedValues = {};
$.getJSON("ajax/test.json", function(data) {
for (var i = 0; i < data.length; i++) {
for (key in data[i]) {
matchedValues[key] = data[i][key];
}
}
console.log(matchedValues); //this should print your object.
});
The data objects must have different keys or they will be overlapsed.

Categories

Resources