0

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?

4
  • try to alert result to see if it's object,and it's correct you have 3 objects Jul 29, 2016 at 4:54
  • That is correct, result is an object, and result.employees is an array of three objects ... the problem is how you are accessing the data ... result.employees[0].firstName will be John for example Jul 29, 2016 at 4:54
  • @JaromandaX Ah, that makes sense. Thank you! Jul 29, 2016 at 5:03
  • No worries, always glad to help Jesus, and possibly a fellow Aussie Jul 29, 2016 at 5:09

1 Answer 1

1

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>');
     });

},
1
  • don't forget to check the green button to accept the answer :p Jul 29, 2016 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.