TheAuzzieJesus TheAuzzieJesus - 4 months ago 14
Javascript Question

Issues loading a JSON file using jQuery and AJAX in PHP

Trying to load the content from a

JSON
file using
jQuery
and
AJAX
in
PHP
but the function is only returning
[object Object],[object Object],[object Object]
.

Here is the JSON file.

{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}


Here is the code I am using.

<!DOCTYPE html>
<html>

<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url: 'testing.txt',
type: 'GET',
dataType: 'json',
success: function(result) {
alert(result['employees']);
},
error: function() {
alert("error");
}
});
});
});
</script>
</head>

<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<button>Get External Content</button>
</body>

</html>


What am I doing wrong?

Answer

Try the following to display you json to the page:

You use the dot selector to select the values of the fields based on the property name,for the employees property is al little different because we have a array, so we loop through it

success: function(result) {
     $('#div1').empty();
     $.each(result.employees,function(i,v){
        $('#div1').append('<h2>'+v.firstName+' - '+v.lastName+'</h2>');
     });

},
Comments