I'm currently attempting to use the Flickr API and javascript to generate a page based on a search query, in this case, dogs. When the line
var hyperLink = "https://www.flickr.com/photos/" + photo.owner + "/" + photo.id + ".jpg";
Runs it states undefined is not an object in regards to photo.owner. I am able to print out photo.owner using console.log(photo.owner) but cannot access it to merely print out the information in the url.
Full code is:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Flickr Experiment</title>
</head>
<body id ="1">
<script>
function jsonFlickrApi(rsp) {
var str = "";
str +="<h1>Doggo piccies from Flickr</h1>";
str +="<h3>Total piccies: " + rsp.photos.photo.length;
var i;
for (i = 0; i <= rsp.photos.photo.length; i++) {
var photo = rsp.photos.photo[i];
var imageTitle = photo.title;
var hyperLink = "https://www.flickr.com/photos/" + photo.owner + "/" + photo.id + ".jpg";
var imgLink = "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg";
str +="<img alt=\"" + imageTitle + "\" src=\"" + imgLink + "\"/>"
}
document.writeln(str);
}
</script>
<script src="https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXf&tags=golden-retriever&per_page=100&format=json">
</script>
</body>
</html>
Arrays are zero based. That means if an array's length is 3, then the highest index is 2. The loop condition must therefore be
i < rsp.photos.photo.length
//^^ strictly smaller, not smaller or equal
If not, you will be accessing an index (namely the length of the array) which doesn't exist, which will result in undefined, the error you are getting.
Simple example:
var arr = [1,2,3];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[arr.length]);
Related
For example, there is a page like below.
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var lookatthis = 11;
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
I want to assign the javascript variable "lookatthis" on debug console.
//apologise for my ambiguous question. I would rather say,
"I want to assign new value to variable "lookatthis" on this web-page using console on explorer."
Thank you for your kind teaching.)
Open debug console and write there:
lookatthis = 20
But this get you nothing
You can use the log method:
console.log(lookatthis);
Anywhere in your script block after your initial assignment of lookatthis, you can write the value to the console with the command:
console.log(lookatthis);
You achieve it by using prompt function
var lookatthis = prompt('Type the lokaltthis value');
If what you want is to be able to 'set' the value of lookatthis, you can use an input and using jquery or pure js get the value of the input and assign it to 'lookatthis'.
Edit: You can also use in the chrome console: lookatthis=25
but as your script loads when page loads, changes will not be shown but the value will be changed
I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>
Hi everybody this code is used to have a list name and id of facebook friends or invited friends if executed on friend list page. I'm trying to count the character of a string in javascript but .length method return always 1. I don't understand why cause I'm counting on a string not an array.
this is my code:
var name_list;
var id_list;
var count_letter_l;
var count_name = 0;
var count_id = 0;
var inputs = document.getElementsByClassName('_2akq _1box');
for(var i=0;i<inputs.length;i++){
var name = inputs[i].getElementsByTagName('span')[0].childNodes[0].nodeValue;
var full_id = inputs[i].getAttribute("data-reactid");
var split_id = full_id.split(':');
var split_two = split_id[1].split('.');
var split_final = split_two[0];
var count_letter = split_final.length;
//console.log(count_letter);
if(name != 'null'){
name_list+= ',' + '"' + name + '"';
id_list += ',' + '"' + split_final + '"';
count_letter_l += ',' + '"' + count_letter + '"';
count_name++;
count_id++;
}
}
console.log(name_list);
console.log('------!!!!!!!!------');
console.log(id_list);
console.log('names = ' + count_name);
console.log('id = ' + count_id);
console.log('letters for esch field = ' + count_letter_l);
I wish to count the character of every id cause in my case when I grab the ids I have some "0" and "1" in the and of the list. I don't know why and I wish to cut them out of the list.
This is an element of _2akq _1box class. you can see it if open firefox firbug and look at facebook front-end html code while you are displaying the friends list
<span class="_2akq _1box" data-reactid=".5q.2.0.0.0.0:0:1:$1543522353.0.0.$2.$text.0.0">
<span data-reactid=".5q.2.0.0.0.0:0:1:$1543522353.0.0.$2.$text.0.0.0">Laura Casali</span>
</span>
the console tell me:
letters for esch field = undefined,"1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1".....
tnx for help
function saveForm() {
var array = [];
array.push(txtTName.value + "," + txtTNumber.value + "," + txtProjName.value + "," + getTotal());
var scores = document.getElementById("scores");
scores.innerHTML += "<br \>" + array[0] + array[1] + array[2];
}
Here's my code. So when a button is pushed it calls "saveForm()" which saves the values into an array and displays them. The first time its called it displays "xxxxx undefined undefined" the next time it calls "yyyyyy undefined undefined". Shouldn't it be returning "xxxxx yyyyy undefined"?
I'm only displaying elements 0,1, and 2 right now for testing purposes.
function saveForm(){
var array = [];
var list = txtTName.value + "," + txtTNumber.value + "," + txtProjName.value + "," + getTotal();
array.push(list);
var scores = document.getElementById("scores");
scores.innerHTML += "<br \>" + array[0] + array[1] + array[2];
}
Here's an edited version of saveForm(). The values don't really matter, I'm more wondering if there's a reason its only changing the first element. Do I need to create array outside of the function?
function saveForm() {
var array = [];
array.push(txtTNumber.value);
array.push(txtTNumber.value);
array.push(txtProjName.value);
array.push(getTotal());
document.getElementById("scores").innerHTML += "<br \>" + array.join(', ');
}
var array = [];
function saveForm(){
....
}
MSDN gives the following Javascript code for querying the Bing Image Search API. It works fine in IE but breaks in Chrome. How can I fix it to be compatible across browsers?
MSDN JSON Code Sample (Image SourceType)
<!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">
<head>
<title>Bing API 2.0 Image Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script id="searchCallback" type="text/javascript" src="">
</script>
<script type="text/javascript">
// Replace the following string with the AppId you received from the
// Bing Developer Center.
var AppId = "AppID Intentionally Omitted";
// Bing API 2.0 code sample demonstrating the use of the
// Image SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=xbox site:microsoft.com"
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var requestScript = document.getElementById("searchCallback");
requestScript.src = requestStr;
}
function SearchCompleted(response)
{
var errors = response.SearchResponse.Errors;
if (errors != null)
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Image results.
DisplayResults(response);
}
}
function DisplayResults(response)
{
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i)
{
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors)
{
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i)
{
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i])
{
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
</script>
</head>
<body onload="Search()">
<div id="output"></div>
</body>
</html>
When I inspect the Javascript using Chrome I see the following error and warning:
Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html.
The unexpected token error seems to refer to searchCallBack. It's not clear where the MIME type warning is coming from.
I don't know if the sample itself will work on Chrome, but the issue is this line:
<script id="searchCallback" type="text/javascript" src="">
You'll have to remove the "src" attribute. Chrome complains about the non-existing source.
This will fix the error:
<script id="searchCallback" type="text/javascript">
Don't bother about the MIME warning. Chrome just complains that the MIME type of the script is incorrect but this should not cause problems.
EDIT:
Here's a working solution for all browsers. Chrome & Co. don't like changing the src attribute of the script tag. Instead they prefer to get a script tag created dynamically.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bing API 2.0 Image Sample</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
// Replace the following string with the AppId you received from the
// Bing Developer Center.
var AppId = "1DB8A37DAB934B531CDC74CF614F386431D69FD3";
// Bing API 2.0 code sample demonstrating the use of the
// Image SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=xbox site:microsoft.com"
+ "&Sources=Image"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Image-specific request fields (optional)
+ "&Image.Count=10"
+ "&Image.Offset=0"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
var elHead= document.getElementsByTagName("head")[0];
var oScript = document.createElement("script");
oScript.type= 'text/javascript';
oScript.src= requestStr;
elHead.appendChild(oScript);
}
function SearchCompleted(response)
{
var errors = response.SearchResponse.Errors;
if (errors != null)
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
// There were no errors in the response. Display the
// Image results.
DisplayResults(response);
}
}
function DisplayResults(response)
{
var output = document.getElementById("output");
var resultsHeader = document.createElement("h4");
var resultsList = document.createElement("ul");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
var results = response.SearchResponse.Image.Results;
// Display the results header.
resultsHeader.innerHTML = "Bing API Version "
+ response.SearchResponse.Version
+ "<br />Image results for "
+ response.SearchResponse.Query.SearchTerms
+ "<br />Displaying "
+ (response.SearchResponse.Image.Offset + 1)
+ " to "
+ (response.SearchResponse.Image.Offset + results.length)
+ " of "
+ response.SearchResponse.Image.Total
+ " results<br />";
// Display the Image results.
var resultsListItem = null;
for (var i = 0; i < results.length; ++i)
{
resultsListItem = document.createElement("li");
resultsList.appendChild(resultsListItem);
resultsListItem.innerHTML = "<a href=\""
+ results[i].MediaUrl
+ "\"><img src=\""
+ results[i].Thumbnail.Url
+ "\"></a><br /><a href=\""
+ results[i].Url
+ "\">"
+ results[i].Title
+ "</a><br />Dimensions: "
+ results[i].Width
+ "x"
+ results[i].Height
+ "<br /><br />";
}
}
function DisplayErrors(errors)
{
var output = document.getElementById("output");
var errorsHeader = document.createElement("h4");
var errorsList = document.createElement("ul");
output.appendChild(errorsHeader);
output.appendChild(errorsList);
// Iterate over the list of errors and display error details.
errorsHeader.innerHTML = "Errors:";
var errorsListItem = null;
for (var i = 0; i < errors.length; ++i)
{
errorsListItem = document.createElement("li");
errorsList.appendChild(errorsListItem);
errorsListItem.innerHTML = "";
for (var errorDetail in errors[i])
{
errorsListItem.innerHTML += errorDetail
+ ": "
+ errors[i][errorDetail]
+ "<br />";
}
errorsListItem.innerHTML += "<br />";
}
}
</script>
</head>
<body onload="Search()">
<div id="output"></div>
</body>
</html>