Send a String from PHP and display it with ajax is simple but how about sending object. In this article, I guide you how to send an Object and display it with ajax json encode.

The keywords to use this technique is JSON.

Step 1: Create php file with this code.

Class Object {
 public $number = "";
 public $name = "";
}

$object = new Object();
$object->number = "1";
$object->name = "PHP";

<span style="color: red;">header('Content-Type: text/json; charset=UTF-8;');
echo json_encode(array("status"=>200,"data"=>$object));</span>

In this code, we will create an object name object with two attribute is number and name. Then we will send this object through ajax and display it in html.
The line 10 and 11 will send header is type json and encode the object in json. Without these line, we cannot send json through ajax.

Step 2: do the ajax request.

$(document).ready(function() {
 $('#btn').click(function(){
  $.ajax({
   dataType: "json",
   url: 'login.php',
   success: function(result){
    var content = "<div style='color: black;'><h2>" + <span style="color: red;">result["data"].number</span> + "--" + <span style="color: red;">result["data"].name</span> + "</h2></div>";
    $('#result').html(content);
   }
  }).fail(function(e) {
  });
 });
});

Line 7 is the way to use json type with attribute from object.
The full code in display file will be.

<!DOCTYPE head PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="login.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>

<style>
body{
margin:0 auto;
max-width: 500px;
padding: 30px;
}
</style>
<body>
 <input id="btn" type="button" value="show array" />
 <div id="result"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
 $('#btn').click(function(){
  $.ajax({
   dataType: "json",
   url: 'login.php',
   success: function(result){
    var content = "<div style='color: black;'><h2>" + result["data"].number + "--" + result["data"].name + "</h2></div>";
    $('#result').html(content);
   }
  }).fail(function(e) {
  });
 });
});
</script>
</html>