Solved

Simple example of making a JSON request required

Posted on 2011-09-23
14
951 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 3
14 Comments
 

Author Comment

by:Austrian_Des
ID: 36586409
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
ID: 36586486
Please show your json string
0
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36586519
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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36586533
0
 

Author Comment

by:Austrian_Des
ID: 36586755
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
ID: 36587044
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
ID: 36587285
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
 
LVL 3

Assisted Solution

by:timhigham
timhigham earned 250 total points
ID: 36592407
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
ID: 36597085
Seems fine to me. Look at below screen shot

screenshot.png
0
 

Author Closing Comment

by:Austrian_Des
ID: 36707875
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
ID: 36707946
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
ID: 36912112
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
ID: 36912537
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
ID: 36921964
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

617 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