I can't make this sample code to load properly in Google Chrome; it loads a blank page. What seems to be wrong with the code?
Code is below:
<!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”>
<body>
<script type="text/javascript">
var myString = “56.02 degrees centigrade”;
var myInt;
var myFloat;
document.write(“\“” + myString + “\“ is “ + parseInt(myString) +
“ as an integer” + “<BR>”);
myInt = parseInt(myString);
document.write(“\“” + myString + “\“ when converted to an integer equals “ +
myInt + “<BR>”);
myFloat = parseFloat(myString); document.write(“\“” + myString +
“\“ when converted to a floating point number equals “ + myFloat);
</script>
</body>
</html>
Dave was absolutely right, it was the quotes. This version, with fixed quotes, loads in my Chrome.
<!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">
<body>
<script type="text/javascript">
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write("\"" + myString + "\" is " + parseInt(myString) +
" as an integer" + "<BR>");
myInt = parseInt(myString);
document.write("\"" + myString + "\" when converted to an integer equals " +
myInt + "<BR>");
myFloat = parseFloat(myString); document.write("\"" + myString +
"\" when converted to a floating point number equals " + myFloat);
</script>
</body>
</html>
Here's what I'm seeing:
Related
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]);
This is the link to the viewable example from the book;http://beginningjs.com/examples/ch2_example7.html
This is my code saved locally; Not sure why it wont load.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title> Chapter 2, Example 7</title>
</head>
<body>
<script>
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write{"\"" + myString + "\" is + "\" + parseInt(myString, 10) +
"as an interger" + "<br/>"};
myInt = parseInt(myString, 10);
document.write("\"" + myString + "\"when converted to an interger equals " + myInt + "<br/>" );
nyFloat = parseFloat(myString);
document.write( "\"" + myString + "\" when converted to a floating point number equals " + myFloat);
document.write(myString);
</script>
</body>
</html>
I think it's loaded but your javascript syntax are wrong.
Use parentheses instead of braces on your first document.write. The script is stuck in that line and the rest of your program doesn't execute, that's why the page doesn't show anything.
Okay There is an error in your first document.write("your string") line you need to use small () braces instead of curly {} braces every time you use document.write("your string"). You have declared variable as var myFloat; and then used it as nyFloat = parseFloat(myString); which is wrong because of typo in nyFloat and (mystring,10) to print value 56.02 at the end. so the correct is myFloat = parseFloat(myString,10); There is no need to write the last line i.e. document.Write(myString); as it is printing the string again at the end. If in future you experience these kind of errors you can see these Javascript errors by using developer tool in your browser and for that you just need to press F12 from your key board as explained in one of comment under your question.
Here is the corrected code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title> Chapter 2, Example 7</title>
</head>
<body>
<script>
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write("\"" + myString + "\" is " + parseInt(myString, 10) + " as an interger" + "<br/>");
myInt = parseInt(myString, 10);
document.write("\"" + myString + "\" when converted to an interger equals " + myInt + "<br/>" );
myFloat = parseFloat(myString, 10);
document.write("\"" + myString + "\" when converted to a floating point number equals " + myFloat);
//document.write(myString);
</script>
</body>
</html>
PLEASE help js file does not work in localhost, when script tag in head.
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="javascript/script.js"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
but when it in body it works.My question .why?
The problem is that your code is executed in head before the body loaded. document.getElementById("demo") won't find the element "demo" because it does not exist yet.
Use it on onload:
window.onload = function() {
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
}
document.getElementById("demo") will try to find an element with id demo but since the page hasn't been rendered completely yet , it won't find anything and return null.
use window.onload.
window.onload = function(){
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
};
The scripts should always be loaded at the bottom of your body, to be sure that DOM is loaded before execution. Alternatively you can use JQuery $(document).ready(function(){ //put your code in here });
This is because when your are putting this js snippet inside head tag it does not know what is <p id="demo"></p>
But when you put it inside body tag, first DOM get parsed then js is executed. You can still put it inside head tag by using window.load.Here is snippet
window.onload=function(){
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
}
WORKING COPY
I'm working through Beginning Javascript but can't get past Chapter 2 finishing exercise 2. The exercise is to correct this bit of code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " theTotal);
</script>
</body>
</html>
I can get the correct total to display using alert, however when I remove the commenting it no longer works.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var intFirstNumber = parseInt(firstNumber, 10);
var intSecondNumber = parseInt(secondNumber, 10);
var theTotal = intFirstNumber + intSecondNumber;
alert(theTotal);
//document.write (intFirstNumber + " added to " + intSecondNumber + " equals " theTotal);
</script>
</body>
</html>
I can't figure out what about my document.write statement is wrong. Any hints? Additionally is there a more elegant way to achieve what I'm doing?
You need another + between the "equals" and theTotal:
document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);
In this context, the + sign means concatenate (append) whatever comes after it to whatever comes before it.
Further Reading:
MDN documentation for string concatenation.
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>