Solved

Prototype and JSON (or XML).

Posted on 2006-11-23
18
1,191 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
 

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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Shoutout to Emily Plummer (http://www.experts-exchange.com/members/eplummer26.html) for giving me this article! She did most of it, I just finished it up and posted it for her :)    Introduction In a previous article (http://www.experts-exchang…
Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

743 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

12 Experts available now in Live!

Get 1:1 Help Now