JavaScript Query Json String from (api.census.gov) - javascript

I have an API which should return some text JSon String.
http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08
I wan to use JavaScript to query this API and display in the HTML element. The code looks like this:
//html
<input type="submit" value="Get City" onclick=" getpop()">
//JS:
function getpop() {
var nereq2 = new XMLHttpRequest();
nereq2.open("GET", "http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08", true);
nereq2.onreadystatechange = function () {
if (nereq2.readyState == 4) {
var temp3 = nereq.response; **//problem start at here, which always return empty*******
document.getElementById("fs").innerHTML = temp3;
};
};
nereq2.send();
}
When I click the link it returns the JSon properly, however when I use the code to query, it returns empty. I don't know whether it related to the browser setup or there are some other issues?

You have a typo. nereq.response should be nereq2.response.
Working JSFiddle - (using https here because JSFiddle requires that)

Related

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

How to set variable value from javascript to JSP?

I need to draw a table dynamically depending on the data store in a database. When the first web page (validator.jsp) is loaded it goes to a dataBase and returns an ArrayList called cert. (cert hast Description, value, etc).
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();%>
After that when the page finishes loading, a javascript function is called (function drawCertificates). This function will draw as many tables as certificates the ArrayList has.
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var i;
for(i=0;i<<%=cert.size()%>;i++){
createTable(i);
}
}
</script>
As you can see in the function create table, the variable text is suppost to change depending on i
text = document.createTextNode("<%=cert.get(i).getDescription()%>");
In order to update that variable i, I first call the JSP setVariable, to update the counter and then I try to use it in getDescription like:
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
I have this setVariable.jsp
<%
int num = Integer.valueOf(request.getParameter("number"));
request.setAttribute("count", num);
request.getRequestDispatcher("VidaDollarsCC.jsp").forward(request, response);
Cookie cookie = new Cookie("countCookie",String.valueOf(num));
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
%>
In other JSP (validator.jsp)I have this javascript function who it supposed to change the variable value.
function setVariable(number){
alert("setting the number " + number);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
}
xmlhttp.open("POST", "setVariable.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("number="+number);
}
In the same jsp (validator.jsp) I have this function to createTable(uniqID) where I need that the number is updated depending on the uniqID because I have an ArrayList which has some information that I want to be shown.
function createTable(uniqID){
setVariable(uniqID);
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
}
But is not working. Does someone knows why? How can I solve it? if you have other ideas that I can implement, that also would be great.
I am assuming that your AJAX call is successfully sending number to setVariable.jsp.
1) You have to realize that AJAX call is a different request and is different then the request you have in your validator.jsp page.
2) You cant write JSP expression from Javascript and have it being resolved to HTML since your JSP needs to be reprocessed by server side.
To answer to your question on how to solve this, we need to know what you are trying to do in the first place.
Update:
1) Looks like the uniqID and count are same number. Why not just use uniqID in your javascript.
2) Why not pass certificate description into the createTable too. Like so:
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();
StringBuilder jsCerts = new StringBuilder("[");
boolean first = true;
for (Certificate cr : certs){
if (!first) jsCerts.append(",");
first = false;
jsCerts.append("\"").append( cr.getDescription() ).append("\"");
}
jsCerts.append("]");
%>
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var certArray = <%=jsCerts.toString()%>;
var i;
for(i=0;i<certArray.length;i++){
createTable(i, certArray[i]);
}
}
</script>
function createTable(uniqID, desc){
setVariable(uniqID);
text = desc;
}
The point here is that you need to write all the necessary data into the HTML to be able to use it in JavaScript, you cant access request attributes from JavaScript.

How to return a url to form action using a javascript function

I want to return a url to form action using javascript function.
I am calling the function like this:
<form action="javascript:getUrl()">
And my function is returning strings of url like this:
function getUrl(){
if(condition)
return "this string url";
else
return "this string url";
}
When I am doing this, the resultant page simply shows the urls in text format on browser instead of loading them.
I am pretty new to these scripting and web designing stuffs.
javascript:getUrl() is not going to be interpreted as JS code, it's just a literally string.
Instead select form element and set its action property:
function getUrl() {
// ...
}
document.querySelector('form').action = getUrl()
Naturally, use more specific selector for your form, id or class.
You can use the id of your form to know the action url.
Javascript :
<script type="text/javascript">
function form_action() {
if (document.getElementById("myFormId").action == "url1.html"){
// do something
}
if (document.getElementById("myFormId").action == "url1.html"){
// do something else
}
// ...
}
</script>
The html form :
<form action="yourUrl" onsubmit="this.action=form_action();" id="myFormId">
...
</form>

Using Local Storage to Store and Display multiple Answers

I'm working on a webpage where i'm trying to display a question, and have viewers submit an answer, which appears on another page. Currently, only the most recent answer is shown on the answer page. I'm not sure how to write my function so that it stores and displays all responses. (I'm new to javascript) Thanks!
<div id=q2 class="question gr">
What is good design?
<input id="q2input" type="text" >
<div class="buttons"> <button onclick="functionTwo()"
class="sbuttons">Submit</button>
<!-- View Answers Button -->
<button id="ViewAnswers2" class="vabuttons" >View Answers</button>
<script type="text/javascript">
document.getElementById("ViewAnswers2").onclick = function () {
location.href = "WhatIsGoodDesign.html";
};
</script>
</div>
<script>
function functionTwo(){
var input = document.getElementById("q2input").value;
console.log(input);
localStorage.setItem("question2", input);
window.location.href = "WhatIsGoodDesign.html";
}
</script>
Use an array instead. Currently, all you are doing is overwriting the current value in the question2 answer slot every time. Arrays are ways to store multiple data values into one variable
function functionTwo() {
var input = document.getElementById("q2input").value;
var answers = JSON.parse(localStorage.getItem("question2answers")) || [];
//Not too sure about the || [];
answers.push(input);
localStorage.setItem("question2answers", JSON.stringify(answers));
window.location.href = "WhatIsGoodDesign.html";
}
You cannot directly put an array into LocalStorage, so you have to pass it in and out as a JSON object. JSON.stringify() will turn it into a string that you can pass into LocalStorage, while JSON.parse() will translate that string back into an array.
You currently overwrite the key question2 with the new answer each time. If you want a list of the the last answers. You would have to do something along the lines of:
function functionTwo(){
var input = document.getElementById("q2input").value;
var numAnswers = localStorage.getItem("question2numAnswers") || 0;
localStorage.setItem("question2answer" + numAnswers.toString(), input);
localStorage.setItem("question2numAnswers", numAnswers + 1);
window.location.href = "WhatIsGoodDesign.html";
}
This way you keep track of the number of answers with question2numAnswers and each answer with question2answer# and you can loop through the answers on your next page by going from 0 to question2numAnswers that you store.

How to display <input type=''text'> without creating a textbox in jquery?

I have a comment box(textarea) in which the user types something and when he hits enter that thing is automatically displayed in 'comment section'. Now when the user hits submit I'm executing the following code,
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
comment.appendTo(commentSection);
By the above code the comment typed by user is dynamically displayed in the commentSection. This works fine but when user types something like,
<input type='text'>
in the comment box then a textbox is created within the comment section. So is there a way through which I could not let this happen?
Thanks in advance.
One way would be to just append the data as .text
Something like this:
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
commentSection.text(comment);
Edit: To append to an existing part of the comment, replace:
commentSection.text(comment);
with:
commentSection.text(commentSection.text() + comment);
You have to convert the string to entities. Define this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
Then run the following code when the user hits enter:
var comment = htmlencode($("#commentBox").val());
var commentSection = $("#commentSection");
comment.appendTo(commentSection);
Try this ,
div.insertAdjacentHTML( 'beforeend', comment);
You can use
var commentText = $("#commentBox").text();
but this do not clean html tags on your string, additionally you can use a function to do this
function RemoveHTMLTags(vals) {
var regX = /(<([^>]+)>)/ig;
var html = vals;
return (html.replace(regX, ""));
}
and then you use:
var finalComment = RemoveHTMLTags(commentText);

Categories

Resources