jQuery ajax getJson example

jQuery ajax getJson method is used to load json data from server using http get method. Lets go through syntax for getJson method.
jQuery.getJSON( url [, data ] [, success ] )
Url: It is url for get request on server
data: Data which you want to send to server with request.
Success : Callback function which get executed when request succeeds.
Data which you send with get request will be in the form of query string.

jQuery getJson example: 

Lets first create the json file named country.json which we are going to read from server. country.json
"countryName" : "India", 
"population" : 10000
Lets create html file named jQueryGetJson.html.
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
  <title>getJson example</title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" language="javascript">
   $(document).ready(function() {
          $.getJSON("country.json", function(country) {
             $("#getJsonDiv").html('<p> Name: ' + country.countryName + '</p>');
             $("#getJsonDiv").append('<p>Population : ' + country.population+ '</p>');
  <div id="getJsonDiv">
 jQuery ajax getJSON example
  <button>Get country data</button>

Lets deploy html file on server and send getJson request.
When you click on Get country data , you will get below output


  • $(document).ready(function() : This function will get called when fully DOM is loaded.
  • $("button").click(function(event) : This function will get called when "get country data" button is clicked.
  •  $.getJSON("country.json", function(country) : Here we are calling getJson method and URL is "country.json".  When request is successfully completed, callback function will be get called.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012