JQuery Ajax with getJSON

From CoderLearner
Jump to: navigation, search

Description

$.getJSON is used with JSON data to implement the get method.

Syntax

  • This method uses get method
   $.getJSON(URL, PARAMETER,CALLBACK_FUNCTION);

Example 1

   $.getJSON('/toURL.php',{id:300,name:'bob'},function(data){
        ....
   });

Example 2

  • Get parameter from element
   var myName = $('#name').val();
   $.getJSON('/toURL.php',{id:300,name:myName},function(data){
        ....
   });

Example 3

  • Get parameter from PHP variable
   var myName = "<?php echo $name ;?>";
   $.getJSON('/toURL.php',{id:300,name:myName},function(data){
        ....
   });

Example 4

Create Table (user_profile table)

CREATE TABLE user_profile
( 
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(200) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY(id)
);

Insert sample records to user_profile table

INSERT INTO user_profile(name,age)
 VALUES('Bob',39),
       ('Jing',41),
       ('Paul',42),
       ('David',40),
       ('Jamy',20),
       ('Christ',28);

user_profile.php contains the json data from MySQL

  • This script queries the MySQL data and it generates the json data
<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);

if (mysqli_connect_errno()) {
	printf("Connect failed: %s<br/>", mysqli_connect_error());
}


$sql = "SELECT id, name, age FROM user_profile";
$result_db = $db->query($sql);
$all_result = $result_db->fetch_all();
echo json_encode($all_result);
$db->close();
?>

pageUser.html

  • This is the page uses the $.getJSON to load the json data from the PHP server site script
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>User Profile List</title>
		<script 
                   type="text/javascript" 
                   src="jquery.min.js"></script>
		<script type="text/javascript" language="javascript">
		       $(document).ready(function() {
				$.getJSON('user_profile.php',null,function(data){
				  if(data) {
					var table = '<table border="1">';
					table += '<tr><td>'
                                             + 'User Information'
                                             + '</td></tr>';
				         $.each(data,function(i,element){
						table +='</tr><td>'
                                                  + element 
                                                    + '</td></tr>';
				         });
					table +='</table>';
				$('#user_profile_content').html(table);
				 }
				else {
						alert('error');
					}
				}); 
			});
		</script>
	</head>
	<body>
		<div id="user_profile_content"></div>
	</body>
</html>

Example 5

  • Generate json from the associative array.
<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);

if (mysqli_connect_errno()) {
	printf("Connect failed: %s<br/>", mysqli_connect_error());
}


$sql = "SELECT id, name, age FROM user_profile";
$result_db = $db->query($sql);
$result = array();
while ($row = $result_db->fetch_assoc()) {
	$result[] = $row;
}

echo json_encode($result);
$db->close();
?>

Display Result

[{"id":"1","name":"Bob","age":"39"},
{"id":"2","name":"Jing","age":"41"},
{"id":"3","name":"Paul","age":"42"},
{"id":"4","name":"David","age":"40"},
{"id":"5","name":"Jamy","age":"20"},
{"id":"6","name":"Christ","age":"28"},
{"id":"7","name":"Johnny","age":"22"},
{"id":"9","name":"Koko","age":"18"}]

use the $.getJSON() method to display the PHP json data which generate from the associative array

$(document).ready(function() {
	$.getJSON('user_profile.php',null,function(data){			
            if(data) {
		//alert(data[0].id);
		var table = '<table border="1">';
		table += '<tr><td>User Id</td>';
                table += '<td>User Name</td><td>User Age</td></tr>';
		$.each(data,function(i,element){
			table +='</tr>';
			table +='<td>'+ element.id + '</td>';
			table +='<td>'+ element.name + '</td>';
			table +='<td>'+ element.age + '</td>';
			table +='</tr>';
		});
		table +='</table>';
	      $('#user_profile_content').html(table);
	    }
	    else {
		alert('error');
	    }
});