Receive JSON result from AJAX with JQuery

Posted on 28-04-2013 21:22 by graham
This tutorial describes how you can call an AJAX action that returns JSON data and parse it using JQuery.

Calling AJAX


Let's say we have an action available at wordgraphs.com/getusers that returns some JSON data, e.g. a list of users:
JSON response
[
{ "name": "Mary Lee", "age": "32" },
{ "name": "Frank Salliman", "age": "61" }
]

We want to make an AJAX call to this service and display the received list of users as an HTML list. To do this, we need to call JQuery's $.get or $.post method, depending on whether the action is available through POST or GET. We also need to make sure to specify the dataType of the call to json:
AJAX call
$.get("http://wordgraphs.com/getusers",
function (data)
{
var htmlString = "";

// iterate over elements of the array
for (i = 0; i < data.length; i++)
{
var user = data[i];
htmlString += "<li>" + user.name + " - age: " + user.age + "</li>";
}

// add the built HTML to DOM
$("#resultContainer").html(htmlString);
},
"json"
);
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems