Use JSON output from Flickr to display images from search - javascript

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.

Related

PHP POST: Setting data variables dynamically from an array

Hi all I'm pretty new to PHP and AJAX and all that good stuff and I'm a little stumped on how to proceed from here in my code.
I have a form that is getting sent and I have an array (subcategories) which contains the form labels to retrieve the values of the fields. The fields and values are getting created dynamically based on a textfile that the user uploads so I don't have any way of knowing what they are.
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
var eachfield = subcategories[i];
//Do something
//#C: selector is working fine, cleaning input
var eachfield = $('#' + eachfield).val().trim();
//push the appropriate values with the fixed stuff to a new array
values.push(eachfield);
}
What I'm trying to do is now to set these variables to some name and send them through $data using AJAX and POST.
Something like the following if I was setting everything statically.
var data = {
dimitypedata: dimitype,
densitydata: density,
velocitydata: velocity,
temperaturedata: temperature,
submitbtnclicked: "submitted"
};
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
I'm not quite sure how to mix these two and it may be partially because of getting a confused and not yet being that great with POST and AJAX calls.
EDIT: It looks like my question was a bit unclear (sorry first post lol) I'm trying to dynamically push values that I take out of an HTML form field. The problem is that the form is generated depending on what the user chooses to upload to the site (so both the fields and the forms. My ultimate goal is to enable the user to edit the dynamically generated form based on a text file that they upload and be able to generate a new text file after editing it on the GUI after clicking on the submit button. I can do this if its static but I'm having trouble figuring out how to do the same if I don't know what the form will contain.
I'm trying to to my data object so I can use it in my AJAX call. Here's a little bit of the PHP code that I would use in the next step if the variables were static:
if(isset($_POST['submitbtnclicked']) && $_POST['submitbtnclicked'] == 'submitted') {
//new instance of model for use
$model = new model();
$dimitypedata = $_POST['dimitypedata'];
$densitydata = $_POST['densitydata'];
$velocitydata = $_POST['velocitydata'];
$temperaturedata = $_POST['temperaturedata'];
For an exact answer, we need to see what the "subcategories" array look like.
If I understood correctly, you would like to put the values in an object instead of an array (values). So the first part would look like:
var data = {};
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
//notice that now field name and field value go in separate variables
var fieldName = subcategories[i];
//#C: selector is working fine, cleaning input
var fieldValue = $('#'+eachfield).val().trim();
//push the appropriate values with the fixed stuff to a data object
data[fieldName] = fieldValue;
}
//and then you send your gathered data
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
If you want to generate your 'data' object using 'values' variable, you can do the next:
values = []; // here your values collected previously
var data = {};
for (var key in values){
data[key] = values[key];
}
//now you can use your data in AJAX

Can I pull JSON from api url and use as json2html input?

I have working on a webpage that displays json data in a html hierarchical structure, using the jQuery plugin json2html.
Currently the json data is entered into a text area and a button is pressed to run the conversion. This is the current function that gets the json from the text area and starts the conversion.
$('#btnVisualize').click(function() {
//Get the value from the input field
var json_string = $('#inputJSON').val();
try
{
//json
//var json = JSON.parse(json_string);
eval("var json=" + json_string);
visualize(json);
}
catch (e)
{
alert("Sorry error in json string, please correct and try again: " + e.message);
}
});
The api that the data is comming from needs a lot of authentication, so I have a seperate javascript file that generates the authenticaton and creates the full url to load the api.
function generateUrl(itemkey) {
var orig = "http://explorerapi.barratthomes.co.uk/v2.0/development/getbyitemkey?ItemKey="+itemkey+"&";
Auth.Auth = createAuth();
var var_pairs = [
{name: "Auth.Utc", val: encodeURI(Auth.Auth.Utc)},
{name: "Auth.RequestId", val: Auth.Auth.RequestId},
{name: "Auth.DeviceId", val: Auth.Auth.DeviceId},
{name: "Auth.Hash", val: Auth.Auth.Hash}];
for(var i=0; i<var_pairs.length; i++) {
orig += (i==0?"":"&")+var_pairs[i].name+"="+var_pairs[i].val;
}
var var_names = ["BrandCode", "ApplicationId", "ApplicationVersion", "LanguageCode", "IsPublished", "MarketingSuiteDevelopmentId", "UserLocation", "Os", "ScreenResolution", "Hierarchical"];
for(var j=0; j<var_names.length; j++) {
orig += "&"+var_names[j]+"="+Auth[var_names[j]];
}
return orig;
}
This is the function that generates the url.
I need to take the url from that function and connect to the api and pass the data directly to the json2html function, so I no longer have to paste the json data into the text area.
I have been looking at $.getJson and $.parseJSON but having no luck, I'm not sure where to go next?
Try this Jsonp to do the fetching the data from the url
function insertIntoTextArea(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'your proper url?callback=insertIntoTextArea';
// insert script to document and load content
document.body.appendChild(script);
You should be able to use $.getJSON like this
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
And then just pass the data object to json2html. However, check with the API that you're connecting to http://explorerapi.barratthomes.co.uk/v2.0/development/getbyitemkey as they might require JSONP (which pretty much just performs a callback function to get around CORS).
See http://api.jquery.com/jquery.getjson/
If the URL includes the string "callback=?" (or similar, as defined by the >server-side API), the request is treated as JSONP instead. See the discussion >of the jsonp data type in $.ajax() for more details.

Creating divs in AJAX loop

I am getting data from the server side using AJAX, I am now trying to populate data from from a list of objects into divs, the problem I am having is that I can not create the div while inside of the foreach loop.
$(document).ready(function () {
var divs = "";
var url = "../Graphs/CreateChart";
$.ajax({
type: 'POST',
url: url,
success: function (data) {
for (var i in data) {
var x = data[i];
for (var j in x) {
var val;
if (x.hasOwnProperty(j)) {
val = x[j].SpName;
if (x[j].SpName != "undefined") {
$('#a').appendTo('#content');
createBarChart("#a", "USP_Charts_BarChart1");
}
}
}
}
}, dataType: "json",
cache: false
});
});
</script>
I am trying to populate where it says "#a" with val and also then I need to populate the div I write with the val for the id, but when I try to put the document.write inside of the loop, I get a blank screen, any ideas why it would do this?
you're trying to append a created variable to your content? Try making the markup a string FIRST then appending it.
To test it try it without data.
$("<h2>HI</h2>").appendTo("#content");
If that works, then make a string that is the markup you want, with the data you need.
$("<a data='"+data.variable+"'></a>").appendTo("#content");
append and appendTo are VERY similar, but you need to use a string, not just an identifier, if the object doesn't exist yet.

Javascript loading CSV file into an array

I am developing a web page in Wordpress. The webpage needs to have a combobox with all counties. I have a dataset in csv format which has some 10k rows for all these counties.
When the user selects a county in the dropdown, I want only the selected county data displayed in the web page. This is my requirement.
In wordpress, my web page I am adding the js file using
<script type="text/javascript" src="http://xxx/wp content/uploads/2014/05/countyList1.js"></script>
and the code for webpage dropdown is
<select name="county" id="county" onload="setCounties();" onchange="getSelectedCountyData();"></select>
In countyList1.js file I have the setCounties() and getSelectedCountyData() functions.
So far I can see the dropdown with counties list. I don't know how to read the CSV file and apply the selected county filter to this list.
I tried the FileReader object and I can load the CSV contents on the web page but I don't want the user to select the CSV. I have the dataset already.
I am trying to use this jquery.csv-0.71 library from this SO post How to read data From *.CSV file using javascript? but I need help.
Here's the code which gets called when a county is selected
function getSelectedCountyData() {
cntrySel = document.getElementById('county');
//selCty = countyList[cntrySel.value];
handleFiles();
}
function handleFiles() {
$(document).ready(function () {
$.ajax({
type: "GET",
url: "D:\Docs\Desktop\csvfile.csv",
dataType: "csv",
success: function (data) { processData(data); }
});
});
}
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 1; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(headers[j] + ":" + data[j]);
}
lines.push(tarr);
}
}
console.log(lines);
drawOutput(lines);
}
function drawOutput(lines) {
//Clear previous data
document.getElementById("output").innerHTML = "";
var table = document.createElement("table");
for (var i = 0; i < lines.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < lines[i].length; j++) {
var firstNameCell = row.insertCell(-1);
firstNameCell.appendChild(document.createTextNode(lines[i][j]));
}
}
document.getElementById("output").appendChild(table);
}
I highly recommend looking into this plugin:
http://github.com/evanplaice/jquery-csv/
I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.
Once you include the plugin above, you can essentially parse the CSV using the following:
$.ajax({
url: "pathto/filename.csv",
async: false,
success: function (csvd) {
data = $.csv.toArrays(csvd);
},
dataType: "text",
complete: function () {
// call a function on complete
}
});
Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.
There are a lot of great examples available on the plugin page to do a variety of things, too.
You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.
Use the FileReader API:
<input type="file" id="file input">
js:
console.log(document.getElementById("file input").files); // list of File objects
var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);
Then parse content as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""
If your not overly worried about the size of the file then it may be easier for you to store the data as a JS object in another file and import it in your . Either synchronously or asynchronously using the syntax <script src="countries.js" async></script>. Saves on you needing to import the file and parse it.
However, i can see why you wouldnt want to rewrite 10000 entries so here's a basic object orientated csv parser i wrote.
function requestCSV(f,c){return new CSVAJAX(f,c);};
function CSVAJAX(filepath,callback)
{
this.request = new XMLHttpRequest();
this.request.timeout = 10000;
this.request.open("GET", filepath, true);
this.request.parent = this;
this.callback = callback;
this.request.onload = function()
{
var d = this.response.split('\n'); /*1st separator*/
var i = d.length;
while(i--)
{
if(d[i] !== "")
d[i] = d[i].split(','); /*2nd separator*/
else
d.splice(i,1);
}
this.parent.response = d;
if(typeof this.parent.callback !== "undefined")
this.parent.callback(d);
};
this.request.send();
};
Which can be used like this;
var foo = requestCSV("csvfile.csv",drawlines(lines));
The first parameter is the file, relative to the position of your html file in this case.
The second parameter is an optional callback function the runs when the file has been completely loaded.
If your file has non-separating commmas then it wont get on with this, as it just creates 2d arrays by chopping at returns and commas. You might want to look into regexp if you need that functionality.
//THIS works
"1234","ABCD" \n
"!#£$" \n
//Gives you
[
[
1234,
'ABCD'
],
[
'!#£$'
]
]
//This DOESN'T!
"12,34","AB,CD" \n
"!#,£$" \n
//Gives you
[
[
'"12',
'34"',
'"AB',
'CD'
]
[
'"!#',
'£$'
]
]
If your not used to the OO methods; they create a new object (like a number, string, array) with their own local functions and variables via a 'constructor' function. Very handy in certain situations. This function could be used to load 10 different files with different callbacks all at the same time(depending on your level of csv love! )
This is what I used to use a csv file into an array. Couldn't get the above answers to work, but this worked for me.
$(document).ready(function() {
"use strict";
$.ajax({
type: "GET",
url: "../files/icd10List.csv",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(icd10Codes) {
"use strict";
var input = $.csv.toArrays(icd10Codes);
$("#test").append(input);
}
Used the jQuery-CSV Plug-in linked above.
The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

fetch json object containing 3 arrays with ajax call and pass arrays to javascript

I have a page that creates the following output:
<script>
var JSONObject = { "groups":['1210103','1210103','1210103','1210405'],
"prices":['279,00','399,00','628,00','129,00'],
"titles":['','','','']
};
</script>
This page is called by an ajax call:
$.ajax({url:plink,success: function(result) { }
I now need to recieve the json arrays and pass them to ordinary javascript arrays.
How do I do that?
I have tried with:
result = jQuery.parseJSON(data);
mygroups = result.groups;
myprices = result.prices;
mylabels = result.titles;
Change your page so that it just produces JSON:
{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}
Note that in JSON, you must use ", not ', for quoting strings.
Have it return a Content-Type header of application/json. If for some reason you can't set the correct Content-Type header on the response, you can force jQuery to treat the response as JSON by adding dataType: 'json' to your ajax call, but it's best to use the correct content-Type.
Then in your ajax call's success callback, result will already be a deserialized object with three properties (groups, prices, titles), which will be JavaScript arrays you can work with.
Live Example | Source
You've said in the comments below that the page is a full HTML page with the embedded script tag and you have no control over it other than the contents of the script tag, because of the CMS you're using.
I strongly suggest moving to a more flexible CMS.
Until/unless you can do that, you can simply receive the page as text and then extract the JSON. Change your script tag to something like this:
<script>
var JSONObject = /*XXX_JSONSTART_XXX*/{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}/*XXX_JSONEND_XXX*/;
</script>
Note the markers. Then you can extract the JSON between the markers, and use $.parseJSON on it. Example:
(function($) {
$.ajax({
url: "http://jsbin.com/ecolok/1",
dataType: "text",
success: function(result) {
var startMarker = "/*XXX_JSONSTART_XXX*/";
var endMarker = "/*XXX_JSONEND_XXX*/";
var start, end;
start = result.indexOf(startMarker);
if (start === -1) {
display("Start marker missing");
}
else {
start += startMarker.length;
end = result.indexOf(endMarker, start);
if (end === -1) {
display("End marker missing");
}
else {
result = $.parseJSON(result.substring(start, end));
display("result.groups.length = " + result.groups.length);
display("result.prices.length = " + result.prices.length);
display("result.titles.length = " + result.titles.length);
}
}
}
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
Live Copy | Source

Categories

Resources