What is JSON and how to use it with Ajax using PHP?

JSON stands for JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections.

$.getJSON( "ajax/country-json.php", function( data ) {
var items = [];
$.each( data, function( key, val ) {
jQuery("#country").append("<option value='"+val['country_id']+"'>"+val[country_name]+"</option>");
});

country-json.php

<?php 
$link = mysql_connect("localhost","username","password"); 
mysql_select_db($link,"jsondb"); 
$sql = "SELECT * FROM countries"; 
$res = mysql_query($sql); 
$rows = array(); 
while($r = mysqli_fetch_assoc($res)) {
 $rows[] = $r;
 } 
print json_encode($rows); ?> 

Leave a Reply