Calling a website and getting JSON information back - javascript

I am not too experienced in javascript on using API's and how to call websites and get information back. I have done this before in Java using HTTP objects and more. I am attempting to make an application where a user can type in a company stock name such as APPL and get back a ton of data like gains, losses, changes, etc. This shouldn't be that hard. I have a html/javascript file with an input textbox for the stock name. This part is easy. But after I tack on the stock name to the end of the URL by concatenation I don't know how to make the call and get the JSON information. There are examples of how to do this in other languages in the web page I am using but not for javascript. I am using this link as a tutorial:
http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime
Here is my javascript code so far: Again this is probably really simple to do. Any help on this would be greatly appreciated and is good to know in the future.
script type="text/javascript">
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
var urlEncoded = "http://finance.google.com/finance/info?client=ig&q=NASDAQ:" + textValue.toString();
for (var i = 0, len = urlEncoded.length; i < len; ++i) {
var object = urlEncoded[i];
confirm(object.toString());
}
}
</script>
I just found the following code for using HTTP GET and tried it out but nothing happens when I click the submit button. Any suggestions on what to do or what's wrong???
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Wow, this is turning out to be a lot more work then I had anticipated. Here is the URL string I am using in my code for yahoo finance. I can navigate to it in the browser and it works like a charm. For the life of me I cannot understand why this isn't working.
var urlEncoded = "http://www.finance.yahoo.com/webservice/v1/symbols/" + textValue.toString() + "/quote?format=json";

You could try jQuery, google and download it.
It's a javascript framework that makes things allot simpler .
$.get( "http://yourur.com/file.php?parameter1=value1&parameter2=value2", function( data ) {
//data now contains whatever it loaded from server
console.log("Loaded from server :", data);
}, "json");

Related

GET from JavaScript, problems parsing XML? Or Maps API errors?

I'm trying to make an HTTP get from Javascript, calling Google Maps to get transit duration from A to B, and then parsing the resulting XML as follows:
function getTransitTime(match) {
var homeBase = '<Address 1>';
var distURL = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&key=API_KEY_I_GOT&mode=transit&arrival_time=1519977600&origins=' + homeBase + '&destinations=' + match;
parser = new DOMParser();
xmlDoc = parser.parseFromString(httpGet( distURL ), "text/xml");
var finRet = $(xmlDoc).find('duration').text()
return finRet;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, true );
xmlHttp.send( null );
return xmlHttp.responseText;
}
I receive both the NoApiKeys and SensorNotRequired errors in the js console. What am I doing wrong?
There are probably even more problems with this:
I'm not sure how to deal with spaces in address 1 (and even worse, "match").
Duration has two sub-fields (one being text), not sure if parsing is correct. Note that my query works correctly in the browser (with the same API key) and the output XML is pasted below:
<DistanceMatrixResponse>
<status>OK</status>
<origin_address>New York, NY, USA</origin_address>
<destination_address>Philadelphia, PA, USA</destination_address>
<row>
<element>
<status>OK</status>
<duration>
<value>5100</value>
<text>1 hour 25 mins</text>
</duration>
<distance>
<value>145447</value>
<text>145 km</text>
</distance>
</element>
</row>
</DistanceMatrixResponse>
Any help? I wandered off trying to make something "simple" work, but ended up in the deep end :|
I've managed to fix this:
First, get permissions to make cross-origin requests to the maps API, by including the following in the extension's manifest.json:
"permissions": ["https://maps.googleapis.com/"]
Next, change:
var finRet = $(xmlDoc).find('duration').text()
to
var finRet = $(xmlDoc).find('duration').find('text').text()
This works because the returned XML has a text tag nested inside the duration tag.
Lastly, the spaces in the URL for the maps call don't really make any difference. Thanks for everyone for reading and contributing. I'm still looking for a cleaner solution if there's one.

Ajax send POST to two URLs

On my website I want to send POST data to two different URLs and slightly modify the data for each URL. One is infusion soft and the other is an API on another one of my websites.
NOTE #1: I will be replacing the URL to my personal API with example text.
NOTE #2: Is it imperative that I set the Content Types, or is there other headers/information I'm missing before I send the Form Data? If so, why the heck would this all run perfectly from desktop? This code used to all be in jQuery but was not working as well, so I tried to rewrite the entire thing in Vanilla JS just to get the idea of a dependency problem out of the way.
NOTE #3: No 'Access-Control-Allow-Origin' header is present on the requested resource.
^ This pertains to both Infusion Soft and my personal API. I'm assuming if it's not even set on Infusion Soft that it's not a problem, especially given the fact that everything works perfectly on desktop.
NOTE #4: Every and ALL selectors match an element. There are no typos and again, this works to 100% on desktop running
Windows 10 Home
Chrome Version 61.0.3163.100 (Official Build) (64-bit)
NOTE #5: The action on the form goes to Infusion Soft. I stop the default from happening so I can work with the data, then send it to our database. After that is done I work with the data again, then let the action attribute run for Infusion Soft - all you can see in the code.
My code is as follows:
<script>
var form = document.getElementById('RequestADemo');
document.getElementById('submitButton').addEventListener('click', processData);
function processData(e){
e.preventDefault();
var phone = document.getElementById('inf_field_Phone1').value;
var formData = new FormData(form);
formData.append('action', 'insertLead');
formData.append('inf_field_Phone', phone);
var oReq = new XMLHttpRequest();
oReq.open('POST', 'http://example.com/api.php', true);
oReq.send(formData);
var fullName = document.getElementById('inf_field_FirstName').value;
var fullNameSplitted = fullName.split(' ');
var firstName = fullNameSplitted[0];
if (fullNameSplitted.length > 1) {
var lastName = fullNameSplitted[1];
}
var formData2 = new FormData(form);
formData2.delete('inf_field_FirstName');
formData2.append('inf_field_FirstName', firstName);
formData2.append('inf_field_LastName', lastName);
var oReq2 = new XMLHttpRequest();
oReq2.open('POST', form.getAttribute('action'), true);
oReq2.send(formData2);
form.reset();
alert('Thanks! We will contact you shortly. Check your email for a confirmation.');
}
</script>
This code works perfect on desktop and submits to both my personal API and Infusion Soft.
In our API we take care of the first name and last name splitting and insert them into separate fields in the database.
However, for Infusion Soft we need to do this before we send the data since we can not control their API.
This is all working as planned on desktop.
On my iPhone7 in Safari, this code inserts into my personal database as planned, but does not even make it to Infusion Soft.
I tested some things with console.log(); and found that
var FormData2 = new FormData(form);
is the line where things break on mobile.
Everything before this line is running perfect on mobile.
Any ideas? I'd really appreciate it!
**UPDATE: **
Here are my new variables and code for the second Request sending to Infusion Soft:
var email = document.getElementById('inf_field_Email').value;
var company = document.getElementById('inf_field_Company').value;
var phone = document.getElementById('inf_field_Phone1').value;
var fullName = document.getElementById('inf_field_FirstName').value;
var fullNameSplitted = fullName.split(' ');
var firstName = fullNameSplitted[0];
if (fullNameSplitted.length > 1) {
var lastName = fullNameSplitted[1];
}
var formData2 = new FormData();
formData2.append('inf_field_FirstName', firstName);
formData2.append('inf_field_LastName', lastName);
formData2.append('inf_field_Email', email);
formData2.append('inf_field_Company', company);
formData2.append('inf_field_Phone1', phone);
var oReq2 = new XMLHttpRequest();
oReq2.open('POST', form.getAttribute('action'), true);
oReq2.send(formData2);
However, this is not working on desktop or mobile! :(
The final alert confirmation however is coming through.
SOLVED
As #Barmar mentioned in the comments, I had to create empty FormData and append all of the values manually. I did this and at first it was not working. What I figured out is that I was appending all the values I wanted to send to Infusion Soft, but the solution was to send ALL hidden fields Infusion Soft gives you in the unstyled HTML forms and their values as well.
I just had to make these appends which were 3 other hidden fields in the form:
formData2.append('inf_form_xid', xid);
formData2.append('inf_form_name', isFormName);
formData2.append('infusionsoft_version', isVersion);
Note that I had already set the variables to their values prior to this code block. Infusion Soft must not accept data unless it receives these values, which makes complete sense.

JSON syntax error on Windows 2008

I'm trying to implement a JSON call to simulate AJAX on a certain page where an AJAX panel isn't a viable option.
I want call my .aspx page when a State is selected from a drop down and populate the Counties drop down.
in my State dropdown, I have this call:
onchange="jsonDropDownLoader('COUNTIES', this, 'Content2_DDLCounties')"
That call is on the page and the code is here:
function jsonDropDownLoader(sType, oParent, oChild) {
var lstrChild = document.getElementById(oChild);
var lstrFilter = ""
if (oParent.value > "") {
lstrFilter = oParent.value
}
lstrChild.options.length = 0;
if (oParent.value > "") {
var JSONobject = {};
var http_request = new XMLHttpRequest();
url = "/AltairWeb.NET/RS/jsonDropDownLoader.aspx?TYPE=" + sType + "&FILTER=" + lstrFilter
http_request.open("GET", url, false);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
JSONobject = JSON.parse(http_request.responseText);
}
};
http_request.send(null);
var JSONarray = eval('(' + http_request.responseText + ')').data
for (var i = 0; i < JSONarray.length; ++i) {
var optn = document.createElement("OPTION");
optn.text = JSONarray[i].text;
optn.value = JSONarray[i].value;
lstrChild.options.add(optn);
}
}
}
It returns a string which I then use to populate the County drop down.
I'm getting data back, but it's not rendering on your QA server. Using the developer tools with IE8, I can see that I have a error on this line:
JSONobject = JSON.parse(http_request.responseText);
it says that JSON is not declared.
It says I also have a syntax error on this line:
var JSONarray = eval('(' + http_request.responseText + ')').data
This works perfectly on my development box. However, my development box has WinXP / IIS 5 on it, whereas, our QA server is a Win2008 server with IIS7.5. We have new development boxes coming, but until then, I'm stuck with the XP machine.
Since it works locally, it seems like it must be a security issue with either Windows or IIS on the QA server, possibly with the http_request call, but I can't find anything via google that has helped me figure this out.
I know I've seen posts that JSON.parse is not supported by IE prior to IE9, but this works perfectly in IE8 when I point to my dev server, but not when I point to the QA server, so it doesn't seem to be a browser issue.
Any ideas?
JSON.parse() is a function of your browser, not the server.
Are you sure the difference is the server ... and not your client browser???
You might also wish to consider using something like jQuery (which can both simplify your coding, and help mediate cross-browser issues like this). for example:
Parse JSON in JavaScript?
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
First, you are using a synchronous call (xhr.open('GET', url, false)) , and you are also using onreadystatechange . This is wrong. Choose one or the other.
https://developer.mozilla.org/en/xmlhttprequest
Next, check your browser support for JSON. See https://stackoverflow.com/a/891306/48082 .
If you are unsure, then use json2.js from json.org.
Finally, do not use eval. Use a proper JSON library.

Can't figure out how to do XMLHttpRequest to google app engine

I'm trying to do a simple POST from a javascript (google chrome extension) to my google app
I can see that the HTTP POST is indeed sent to the GAE server, but I can't figure how to transfer a simple text string, and use it in the google app.
The goal: send a string from the javascript with xmlhttpRequest, show this string on google-app webpage.
Here's the code of the javascript:
function onRequest(request, sender, sendResponse) {
var url = request;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myapp.appspot.com");
xhr.send(url);
// Return nothing to let the connection be cleaned up.
sendResponse({});
};
Here's how I deal with the post in the server side:
def post(self):
url1 = str(self.request.get('url1'))
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('<p>URL is: %s</p>' % url1)
When I look at the POST response I see
<p>URL is: </p>
where is the var url that was sent?
I got it to work, in a different way. Instead of XMLHttpRequest, I used jquery:
$.post("http://myapp.appspot.com", { url1: request});
and it worked :)
BTW, I also discovered that if you want the chrome extension's html to use jquery, you need to do
<script src="jquery-1.5.1.js"></script>
<script> your code here </script>
(I'm sure it's basic for you guys but fresh for me :)
The content you include with xhr.send() will be in self.request.body, if it's not specified in CGI format. For your simple test, you might also try xhr.send("url1=" + request).

Json problem in fetching data

<script>
function jsonfunc(){
var data ="publick="+document.getElementById("publickeyval").value+"&privatek="+document.getElementById("privatekeyval").value;
var url="http://www.remoteapiserver.com/example_api/example_adcpatchaapi.php?"+data;
alert(url);
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if (http_request.readyState == 4){
alert(http_request.responseText+"#"); // showing only # //
my_JSON_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
}
</script>
I was as asked my question as per comment i read Json and writing above code in my php page.But still this is giving problem.I am not getting fetched dada from remote server.I am getting only "#" in alert box.
I highly recommend a JavaScript Framework like jQuery for this kind of stuff. It definitely makes this a lot easier. jQuery lets you do cross-domain requests, if you use JSONP (take a look at the docs). The code would look something like this:
$.getJSON(yourUrlGoesHere, function(data) { // ready callback
// data is an object; no need to parse it manually.
});
Sometimes it't better use some library:
JQuery or Moootools: http://mootools.net/docs/core/Request/Request.JSON
Implement this in native JS is difficulty if we want use it in all browsers ;)

Categories

Resources