Solved

Simple example of making a JSON request required

Posted on 2011-09-23
14
927 Views
Last Modified: 2012-05-12
Hi All,

I am new to JavaScript and need help to understand how to code a request for a JSON object.

I know the URL and if I type it into a browser the response I get is good.

What I can't find anywhere is a SIMPLE example of the core code to make 1 request and display the reply, or one element of the reply.

Could someone please post the simplest possible, but complete, code that will do this?

Thanks,

Des
0
Comment
Question by:Austrian_Des
  • 6
  • 5
  • 3
14 Comments
 

Author Comment

by:Austrian_Des
Comment Utility
Sorry, should've added that it'd be great if the page code could be in ASP.

Thanks

Des
0
 
LVL 17

Expert Comment

by:sonawanekiran
Comment Utility
Please show your json string
0
 
LVL 17

Expert Comment

by:sonawanekiran
Comment Utility
Try below code. Simple html and jquery

  <html>
  <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
  <script>
  $(document).ready(function(){
      var myJSONObject = [
            {"FirstName": "Jeff", "LastName": "Sanford"},
        {"FirstName": "Bob", "LastName": "Worly"},
        {"FirstName": "Robert", "LastName": "English"}
    ];

    
    $.each(eval(myJSONObject),function(i,obj){
            alert(obj.FirstName + " " + obj.LastName);
          });
    });
  
  </script>
  <title>Kiran Test</title>
  </head>
  <body>
  
  </body>
  </html>

Open in new window

0
 
LVL 17

Expert Comment

by:sonawanekiran
Comment Utility
0
 

Author Comment

by:Austrian_Des
Comment Utility
Hi,

Thanks for your quick response.

I don't think I explained my problem clearly.

I want to request JSON data from this URL:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"

What I don't know how to do is form the "request" code ...

In your example you have hard coded the data, I need to get it from Google ...

I have searched everywhere for a SIMPLE example but it seems that every example is designed purely to demonstrate the wonderfulness of the coder and not to focus on the very core of the technology being "explained".

On Google's own site they have pages of documentation and it boils down to this as their example:

for (i = 0; i < myJSONResult.results.length; i++) {  
myAddress[i] = myJSONResult.results[i].formatted_address;
}

Open in new window


but no information on how to construct "myJSONResult". I'm sure it's blindingly obvious to everyone how to do it but it's not to me ...

So any help you can give would be great!
0
 
LVL 17

Accepted Solution

by:
sonawanekiran earned 250 total points
Comment Utility
Ok. Look at this example to make call to geocode. I added alert to show the address.

<html>
  <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
  <script>
  $(document).ready(function(){
    $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false', function(myJSONResult){
      var myAddress = [];
      for (i = 0; i < myJSONResult.results.length; i++) {
        myAddress[i] = myJSONResult.results[i].formatted_address;
        alert(myAddress[i])
      }
      
    });
  });

  </script>
  <title>Kiran Test</title>
  </head>
  <body>
  
  </body>
  </html>

Open in new window

0
 

Author Comment

by:Austrian_Des
Comment Utility
Hi thanks again for your reply,

I'm afraid that when I run this code it doesn't create the alert.

Do you have a working example I could try anywhere?

Thanks,

Des
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 3

Assisted Solution

by:timhigham
timhigham earned 250 total points
Comment Utility
I think you need to look at how to make an HTTPRequest, info at:
http://www.ibm.com/developerworks/web/library/wa-httpget/

Note the line in ' function process '
document.getElementById("output").value = xmlDoc.responseText ;

'responseText' is equiv to Google e.g.  'myJSONResult'
This can be altered to process, or call a function to parse (with responseText as argument),  the string returned, which in this case will be the JSON object.

I'm not sure about the small snippet of Google code, however you can use eval if the request is to a trusted source, so:

var myJSONResult=eval(responseText);
alert(myJSONResult["formatted_address"]);

should give test alert with text
1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA

0
 
LVL 17

Expert Comment

by:sonawanekiran
Comment Utility
Seems fine to me. Look at below screen shot

screenshot.png
0
 

Author Closing Comment

by:Austrian_Des
Comment Utility
Thanks for your help on this, I now realise I need to re-think my question as I am really struggling with "JavaScript" which as far as I can see is a client i.e. "browser" technology whereas what I need is to run my code at the server to geocode data in an SQL table (probably via ASP) - And yes I know that's NOT the question I asked ;-) Your support with the JavaScript has helped me focus on my real needs and you each provided useful info, hence the shared points.
0
 

Author Comment

by:Austrian_Des
Comment Utility
I worked it out!! If anyone is interested this code performs the very most basic part of the server based GeoCode retreval, from here it's "just" a case of parsing the reply and storing in a cache (db):


<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Google GeoCode</title>
</head>

<body>

	<%
	url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
	set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP") 
	xmlhttp.open "GET", url, false 
	xmlhttp.send "" 
	response.write("xmlhttp.responseText= "&xmlhttp.responseText)
	set xmlhttp = nothing
	%>

</body>
</html>

Open in new window

0
 
LVL 3

Expert Comment

by:timhigham
Comment Utility
Note server side processing should only be considered IF it is unsuitable for it to be done client-side.
For what I understand, while your serverside code obviously works, but it can also be acheived clientside.

WHY BOTHER ?

Presumably you want a site as sucessful as possible ?..
Remember that the server will have to process for ALL users visiting at the same time.
You get popular, you have on average 10 visitors at one time, the site is instantly 10 times slower.
A virtual server can be even worse, limiting concurrent visitors per account may lead to requests being queued or even dropped.
Therefore the more popular you get the worse the performance.
Or if possible simply send the client the processing instructions and move onto the next client with no processing.
This additionally avoids the issue where continual requests from the same IP (the server) might not be allowed to third party services - client side processing means a different IP for each request.

I very much encourage you to learn Javascript if only for this reason.
0
 

Author Comment

by:Austrian_Des
Comment Utility
timhigham: Thanks for your encouragement but I'm really not sure that GeoCoding the contents of a SQL Table should be undertaken "clientside". This isn't a process that needs to be undertaken whenever a user visits the site but rather once to establish the data and then only again if new data is added.

Are you suggesting that this is a good candidate for some clientside script? It seems to me to put an unnecessary load on the network and shift data back and forth to no great purpose, but if I have misunderstood I'd be grateful for some clarification.

That having been said I am certain that furthering my JavaScript knowledge would be invaluable.

Des
0
 
LVL 3

Expert Comment

by:timhigham
Comment Utility
I have been working on both these precise issues for a few months now.
Is there any specific need to collect GEODATA in your own database when this is accessable on several other servers?
Visit for example the Googlemaps API site.

http://code.google.com/apis/maps/documentation/javascript/reference.html

I simply mention this as the network from YOU to YOUR client simply would be a Latitude and Longitude string estimated at max precision 50 bytes. This would hit the network at 400bits / 0.0004 seconds transfer time for a 1Mbps connection.

Minimal Load !!

Let me know what you think, or if I am not understanding what you are trying to acheive.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

This article discusses how to create an extensible mechanism for linked drop downs.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now