Get data from JSON file using jQuery and Ajax


To retrieve data from JSON file using jQuery and Ajax, The jQuery.getJSON( url, [data], [callback]) method loads JSON data from the server using a GET HTTP request.

Here is the description of all the parameters used by this method:

  1. url - A string containing the URL to which the request is sent
  2. data - This optional parameter represents key/value pairs that will be sent to the server.
  3. callback - This optional parameter represents a function to be executed whenever the data is loaded successfully.

Let’s say we have the following JSON content in employee.json file

{
    "name": "Rahul",
    "age": "30",
    "sex": "male"
}

The following is the code snippet showing the usage of this method:

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Adding two number in jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> 
<script>
$(document).ready(function () {
$("#employeeid").click(function (event) {
$.getJSON('employee.json', function (response) {
$('#stage').html('<p> Name: ' + response.name + '</p>');
$('#stage').append('<p>Age : ' + response.age + '</p>');
$('#stage').append('<p> Sex: ' + response.sex + '</p>');
});
});
});
</script>
</head>
<body>
<input type="button" id="employeeid" value="Load Employee Data" />
<br />
<div id="stage" style="background:green; color:white"> 
</div>
</body>
</html>

Output

jquery and Ajax with Json data Example

Now click to load json data.

jquery and Ajax with Json data Example
Next