$.getJSON() requests JSON data with an HTTP GET request and parses the response before your callback runs. It is useful for lightweight APIs, lookup data and database-backed suggestion endpoints.
$.getJSON(
"json1.php",
function ( data ) {
console.log( data );
}
);
$.getJSON(
"json1.php"
)
.done(function ( data ) {
$( "#d1" ).empty();
$.each(
data,
function ( key, value ) {
$( "<div>" )
.text(
key + " => " + value
)
.appendTo( "#d1" );
}
);
})
.fail(function () {
$( "#d1" ).text(
"Unable to load JSON data."
);
});
$.getJSON(
"json2.php"
)
.done(function ( response ) {
$.each(
response.data,
function ( index, row ) {
$( "<div>" )
.text(
row.id + " | " +
row.name + " | " +
row.mark
)
.appendTo( "#d2" );
}
);
});
$.getJSON(
"json3.php"
)
.done(function ( response ) {
console.log(
response.data,
response.value.message
);
});
$.getJSON(
"student-data.php",
{
class: "Four",
limit: 20
}
).done(function ( rows ) {
console.log( rows );
});
jQuery URL-encodes the data object. Avoid manually concatenating user input into the query string.
header(
'Content-Type: application/json; charset=utf-8'
);
echo json_encode(
$data,
JSON_UNESCAPED_UNICODE
);
See PHP JSON and JSON data formatting.
Live getJSON demo with three JSON shapes →
Download the original getJSON example ZIP
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.