Solved

jQuery Ajax HowTo: Loop through JSON Results

Posted on 2010-08-28
7
1,171 Views
Last Modified: 2012-05-10
Please note: I'm brand spanking new to jQuery ajax, so complete explanations are better than pseudo-code.

The Problem
==========

1. I am running this sample bible search query found here
http://api.biblia.com/docs/Samples

2. I am working on the example which reads "Search the LEB for “bread”, and return the top 20 results in JSON format"  the URL for the service is http://api.biblia.com/v1/bible/search/LEB.js?query=bread&mode=verse&start=0&limit=20&key=abc123  (Since this has a key you must go to the site and click on the link to see the results OR see the output below)

3. For the life of me, I cannot figure out HOW to get at the Results section to loop through each "title" and "preview" field.

here is what comes back from the sample query...
{
  "resultCount": 33,
  "hitCount": 87,
  "start": 0,
  "limit": 20,
  "results": [
    {
      "title": "John 6:5",
      "preview": "Then Jesus, when he looked up and saw that a large crowd was coming to him, said to Philip, “Where can we buy bread so that these people can eat?”"
    },
    {
      "title": "Matthew 16:5",
      "preview": "And when the disciples arrived at the other side, they had forgotten to take bread."
    },
    {
      "title": "John 13:18",
      "preview": "“I am not speaking about all of you. I know whom I have chosen, but in order that the scripture would be fulfilled, ‘The one who eats my bread has lifted up his heel against me.’"
    },
    {
      "title": "1 Corinthians 11:23",
      "preview": "For I received from the Lord what I also passed on to you, that the Lord Jesus, on the night in which he was betrayed, took bread,"
    },
    {
      "title": "1 Corinthians 10:16",
      "preview": "The cup of blessing which we bless, is it not a participation in the blood of Christ? The bread which we break, is it not a participation in the body of Christ?"
    },
    {
      "title": "2 Thessalonians 3:8",
      "preview": "nor did we eat bread from anyone without paying, but with toil and labor, we were working night and day in order not to be a burden to any of you,"
    },
    {
      "title": "Mark 8:4",
      "preview": "And his disciples answered him, “Where is anyone able to feed these people with bread here in the desert?”"
    },
    {
      "title": "Matthew 15:2",
      "preview": "“Why do your disciples break the tradition of the elders? For they do not wash their hands when they eat a meal.”"
    },
    {
      "title": "Matthew 4:3",
      "preview": "And the tempter approached and said to him, “If you are the Son of God, order that these stones become bread.”"
    },
    {
      "title": "Mark 7:2",
      "preview": "And they saw that some of his disciples were eating their bread with unclean—that is, unwashed—hands."
    },
    {
      "title": "Acts 20:6",
      "preview": "And we sailed away from Philippi after the days of Unleavened Bread and came to them at Troas within five days, where we stayed seven days."
    },
    {
      "title": "1 Corinthians 5:8",
      "preview": "So then, let us celebrate the feast, not with the old leaven or with the leaven of wickedness and sinfulness, but with the unleavened bread of sincerity and truth."
    },
    {
      "title": "John 21:9",
      "preview": "So when they got out on the land, they saw a charcoal fire laid there, and a fish lying on it, and bread."
    },
    {
      "title": "2 Corinthians 9:10",
      "preview": "Now the one who supplies seed to the sower and bread for food will provide and multiply your seed, and will cause the harvest of your righteousness to grow,"
    },
    {
      "title": "Mark 14:1",
      "preview": "Now after two days it was the Passover and the feast of Unleavened Bread, and the chief priests and the scribes were seeking how, after arresting him by stealth, they could kill him."
    },
    {
      "title": "Luke 14:1",
      "preview": "And it happened that when he came to the house of a certain one of the leaders of the Pharisees on a Sabbath to eat a meal, they were watching him closely."
    },
    {
      "title": "Acts 2:42",
      "preview": "And they were devoting themselves to the teaching of the apostles and to fellowship, to the breaking of bread and to prayers."
    },
    {
      "title": "Luke 4:3",
      "preview": "So the devil said to him, “If you are the Son of God, order this stone that it become bread!”"
    },
    {
      "title": "Luke 22:1",
      "preview": "Now the feast of Unleavened Bread (which is called Passover) was drawing near."
    },
    {
      "title": "Luke 24:30",
      "preview": "And it happened that when he reclined at the table with them, he took the bread and gave thanks, and after breaking it, he gave it to them."
    }
  ]
}

Open in new window


0
Comment
Question by:the_sleeper
  • 3
  • 3
7 Comments
 

Author Comment

by:the_sleeper
Comment Utility
I was using $.getJSON and getting...nothing.

What am I doing wrong.

thx, sleeper
0
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
Comment Utility
Without seeing your code it's hard to tell what you're doing wrong.  Here's an example.
<html>

<head>	

<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>



<script language="javascript">



	$.ajax( {

		url: 'http://api.biblia.com/v1/bible/search/LEB',

		dataType: 'jsonp',

		data: {

			query : 'bread',

			mode : 'verse',

			start: 0,

			limit: 5,

			key: 'fd37d8f28e95d3be8cb4fbc37e15e18e' },



		success: function(data) {



			var results = data.results;



			for (var i=0; i < results.length; i++) {

				alert( results[i].title + '\n' + results[i].preview);

			}	

		}		

	});



</script>



</head>

<body>

	<p>Example</p>

</body>

</html>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
Use : data.bibles[i].title


$.getJSON("leb.php", function(data) {
			var a = data.bibles;
			for(i=0;i<a.length;i++) {
				alert("title " + i + " : " + a[i].title);
			}
		});

Open in new window

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 82

Expert Comment

by:leakim971
Comment Utility
You may use this to play with your json object : http://jsonviewer.stack.hu/

test page :

(replace leb.php with your url)
<!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=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="javascript">
	$(document).ready(function() {
		$.getJSON("leb.php", function(data) {
			var a = data.bibles;
			for(i=0;i<a.length;i++) {
				alert("title " + i + " : " + a[i].title);
			}
		});
	});
</script>
</head>
<body>
</body>
</html>

Open in new window

0
 

Author Closing Comment

by:the_sleeper
Comment Utility
Excellent! Plus I understand it! It's funny how just reading some great code (as opposed to a ton of pseudo-code) can shed so much light on us, the befuddled masses!

thx clockwatcher

sleeper

0
 

Author Comment

by:the_sleeper
Comment Utility
@leakim971:

Thanks for responding. When I ran your sample (with my url, of course) I got "data is null" error, that kept showing up in my example (using $.getJSON). I have no idea why. I do appreciate your attempt at solving the problem using $.getJSON, But I must confess... I like the lower level $.ajax call (for all the wonderful options at my disposal). But true, the questions dealt with WHY $.getJSON was not working. But as with your example, I got the same error (data is null). I have a fix, but truly, that $.getJSON thing still bugs me..

Props for the link to http://jsonviewer.stack.hu/

thanks again,
sleeper
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
No worries, this is the game.
I don't know why but I get a json object with member << bibles >> and not << results >>
I was thinking this is your issue...
Congratulations to @clockwatcher!
Have a nice day.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

To properly understand GitHub, let’s divide it into two words ‘Git’ and ‘Hub’. Git is basically a ‘Distribution Version Control’ (DVC) and ‘Source Code Management’ (SCM) system widely used by software programmers while Hub means the efficient centre…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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)
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

744 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