Solved

Prototype and JSON (or XML).

Posted on 2006-11-23
18
1,197 Views
Last Modified: 2013-11-19
Hi all,
Firstly, I'm new to prototype, & am trying to use the version 1.5.0_rc1.

I'm trying to get prototype to dynamically read JSON formatted data & display it in a textbox.
I got the URL from http://developer.yahoo.com/common/json.html
but I'm not sure I'm formatting it correctly for prototype!
The URL is:
http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&output=json

Here's my code:

<!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>Prototype Test</title>
<script type="text/javascript" src="prototype.js"></script>

<script>
      function updateTextbox()
      {
            var url = 'http://api.search.yahoo.com/ImageSearchService/V1/imageSearch';
            var pars = 'appid=YahooDemo&query=Madonna&output=json';

            var myAjax = new Ajax.Request(
                  url,
                  {
                        method: 'get',
                        parameters: pars,
                        onComplete: showResponse
                  });
      }

      function showResponse(originalRequest)
      {
            //put returned XML in the textarea
            $('result').value = originalRequest.responseText;
      }
</script>
</head>

<body>
<select size="3" onchange="updateTextbox()">
      <option selected="selected" value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
</select>
<br>
<textarea id=result cols=60 rows=10 ></textarea>
</body>
</html>


Is there anyone that can help...PLEEEEASEEE?
I'd even be happy with XML coming back into the textbox (on FireFox & IE browsers)!
Thanks!
Fal
0
Comment
Question by:AlbertPWilliams
  • 6
  • 5
  • 4
18 Comments
 
LVL 6

Expert Comment

by:aescnt
ID: 18004227
What response/error do you get? Looks ok to me. You're probably getting a script error somewhere that you're not catching. What browser are you using too?
Also you can try onSuccess instead of onComplete, tho i'm not sure if that'd help at all..
0
 
LVL 6

Expert Comment

by:aescnt
ID: 18004231
Also <script type="text/javascript"> since (I think) javascript is not the default script language for IE.
0
 

Author Comment

by:AlbertPWilliams
ID: 18006603
Hi aescnt,
Thanks for the advice!
I've changed them now to what you suggested:

<!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>Prototype Test</title>
<script type="text/javascript" src="prototype.js"></script>

<script type="text/javascript">
     function updateTextbox()
     {
          var url = 'http://api.search.yahoo.com/ImageSearchService/V1/imageSearch';
          var pars = 'appid=YahooDemo&query=Madonna&output=json';

          var myAjax = new Ajax.Request(
               url,
               {
                    method: 'get',
                    parameters: pars,
                    onSuccess: showResponse
               });
     }

     function showResponse(originalRequest)
     {
          //put returned XML in the textarea
          $('result').value = originalRequest.responseText;
     }
</script>
</head>

<body>
<select size="3" onchange="updateTextbox()">
     <option selected="selected" value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
</select>
<br>
<textarea id=result cols=60 rows=10 ></textarea>
</body>
</html>

But still not working, is it working for you?
I'm using FireFox 1.5.0.8
Any ideas?
Best,
Fal
0
Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

 

Author Comment

by:AlbertPWilliams
ID: 18006608
By the way, I'm getting no error!
Is it working for you?
Best,
Al
0
 
LVL 6

Expert Comment

by:aescnt
ID: 18006648
I dont have your version of prototype so I can't quite try it, sorry. :( Are you calling it from a webpage, or locally?
0
 

Author Comment

by:AlbertPWilliams
ID: 18006717
Hi,
I'm calling it locally, but I've now changed the version to version 1.4.0 & still no joy!
I'm not been forced to use a specific version!
Can that be tested?
Thanks,
Fal
0
 
LVL 1

Expert Comment

by:Arathalion
ID: 18008789
You'll need to paste a copy of prototype.js for anybody to be able to test it.
0
 
LVL 6

Expert Comment

by:aescnt
ID: 18010202
Arthalion, google for prototype.js and you'll find it. hehe
0
 
LVL 1

Expert Comment

by:Arathalion
ID: 18012163
aescnt: Do you need to use prototype? The code is not working for me, but it would be easy to extract the information using no includes, just a custom AJAX handler.
Also, can you clarify on the format you want the returned format to be? At the top you mention JSON, but you have included no JSON parser. And in one comment (in the code) you mention XML, which is more do-able, and you don't need a parser, it's inbuilt.
0
 
LVL 6

Expert Comment

by:aescnt
ID: 18013369
Arathalion, Ajax.Request is prototype.js's AJAX handler -- yes you can make your own, but I think the asker is just trying and get it (prototype.js's AJAX helper) to work.
And there's no JSON parser because the concern first is trying to get the AJAX part to work (he's not getting a response right now) -- the JSON part will come easy after that.

Btw, the code above works for URLs in the same domain (i.e., url = 'myfile.php'), I've tried it, but I'm guessing you can't access Yahoo! because of some security precaution. (Using XMLHttpRequest() to another domain, like yahoo.com, isn't allowed by browsers.)

Do you have a PHP system you can test this with? Maybe we can make some sort of proxy to tunnel to another domain (like yahoo.com).
0
 

Author Comment

by:AlbertPWilliams
ID: 18029415
Hi all,
Thanks for all the replies & ideas!
Firstly, as mentioned, the version of Prototype is the 1.4.0 version available here: http://prototype.conio.net/
Please see my code below that shows 2 methods of dynamically retriving JSON data on a seperate domain, namely Yahoo's.

The first method get's the data during loading of the page, so if the data changes on yahoo's page the copy of the data is no longer current! :-(

The second method loads up the JSON data everytime the user hovers over the "Hover for alert showing LATEST data from Yahoo JSON feed." link.
Therefore if the yahoo data changed then this would be seen. :-)

The second method suits me because I only want to load the JSON data when it's required by the user, from an even such as onmouseover.
Also the user should be shown the latest data.

I need to show a simple floating div popup (i.e. not an windows alert popup) which shows the user dynamiclly loaded JSON data.
As you can see, the prototype.js file isn't been used anywhere.
So can someone please advise me whether to use prototype for this, or is there an easy way to do this by hard coding it further?


<!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>Prototype Test</title>
<script src="../dist/prototype.js" type="text/javascript"></script>


<!-- Code to load Yahoo's JSON web service data. -->
<script type="text/javascript">
var yahooResponseOnLoad = {};
function jsonTest(json) {
      yahooResponseOnLoad = json
}
</script>

<script type="text/javascript" src="http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=manalang&query=ajax&output=json&callback=jsonTest"></script>

<script type="text/javascript">
 <!--  To display some of Yahoo's JSON web service data. -->
function alertFromYahooFeed() {
      alert("totalResultsReturned="+ yahooResponseOnLoad.ResultSet.totalResultsReturned);
}
</script>



<!-- Code to both load a fresh copy of Yahoo's JSON web service & immediately after display some of it's content. -->
<script type="text/javascript">
function alertLatestFromYahooFeed() {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=manalang&query=ajax&output=json&callback=displaySampleJSON';
      document.getElementsByTagName('head')[0].appendChild(script);
}

var yahooResponseDynamicallyLoaded = {};
function displaySampleJSON(json) {
      yahooResponseDynamicallyLoaded = json;
      alert("totalResultsAvailable="+ yahooResponseDynamicallyLoaded.ResultSet.totalResultsAvailable);
}
</script>


</head>
<body>
<a href="#" onmouseover="alertFromYahooFeed()">Hover for alert showing data from Yahoo JSON feed.</a>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="#" onmouseover="alertLatestFromYahooFeed()">Hover for alert showing LATEST data from Yahoo JSON feed.</a>
</body>
</html>
0
 

Author Comment

by:AlbertPWilliams
ID: 18029439
By the way, a site that helped me was:
http://manalang.com/wp-content/yahoo-json-example.htm
 
0
 

Author Comment

by:AlbertPWilliams
ID: 18038804
As already mentioned:
I need to show a simple floating div popup (i.e. not an windows alert popup) which shows the user dynamiclly loaded JSON data.
As you can see, the prototype.js file isn't been used anywhere.
So can someone please advise me whether to use prototype for this, or is there an easy way to do this by hard coding it further?
Anyone?
Thanks!
0
 
LVL 1

Accepted Solution

by:
Arathalion earned 500 total points
ID: 18044108
Ok, due to cross-site browser security, you cannot directly access the Yahoo domain from another domain.

Therefore, you need a proxy of some sort.

Yahoo have a tutorial for a PHP proxy: http://developer.yahoo.com/javascript/samples/proxy/php_proxy_simple.txt

Here is code I have used for an AJAX request popup DIV. All you need to do is replace your proxy URL with the one I've put in there



<!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>Non-Prototype Test</title>

<script type="text/javascript">
var IE = document.all?true:false

function GetXmlHttpObject(){
      var objXMLHttp=null;
      if (window.XMLHttpRequest){
            objXMLHttp=new XMLHttpRequest();}
      else if (window.ActiveXObject){
            objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");}
      if (objXMLHttp==null){
            alert ("Browser does not support HTTP Request");
            return;}
      return objXMLHttp}

function hidePopup(){document.getElementById('tip').style.visibility = 'hidden';}

function popupTaskDetails(e,searchData)
{
      //popup div code
      document.getElementById('tip').innerHTML = "Loading...";
      if (IE){
            coordX = event.clientX + document.body.scrollLeft;
            coordY = event.clientY + document.body.scrollTop;}
      else{
            coordX = e.pageX;
            coordY = e.pageY;}
      var t = document.getElementById('tip').style;
      t.left = coordX+15+"px";
      t.top = coordY+15+"px";
      t.visibility = 'visible';
      
      xmlHttp=GetXmlHttpObject();
      var url="[YOUR PROXY URL HERE]"+searchData;
      xmlHttp.onreadystatechange=showResults;
      xmlHttp.open("GET",url,true);
      xmlHttp.send(null)
}
function showResults(){
      if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
            document.getElementById('tip').innerHTML = xmlHttp.responseText;}
}
</script>

</head><body>
<div id="tip" style="visibility: hidden; position:absolute; z-index: 100;"></div>
<a href="#" onmouseover="popupTaskDetails(event,'test')" onmouseout="hidePopup()">Hover for alert showing data.</a>
</body></html>
0
 
LVL 1

Expert Comment

by:Arathalion
ID: 18256063
A perfect solution was impossible - I linked to what was needed from elsewhere (see Yahoo link) and included functional source code for the rest. Combined, it gives a working solution to his problem.
0

Featured Post

ScreenConnect 6.0 Free Trial

Discover new time-saving features in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

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

Suggested Solutions

Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

773 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