Jump to content

Need help displaying json data in html


imgrooot

Recommended Posts

I am retrieving data from a third party's API using AJAX method. I would like to do two things.

1. Display the data records on a page.

2. Create a pagination on the page to display records more efficiently. I am expecting to retrieve possibly hundreds of records. I can normally do this using PHP but since I am retrieving the records using AJAX, the pagination is gonna be a challenge. 

First things first is to display the records. Here is my AJAX code.

It displays the log data fine. But it doesn't display any data in the "output" div. And it gives this error in the console.

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Object.success
<div class="output"></div>

<script>
  $.ajax ({
    type: 'GET',
    url: "https://3rdpartywebsite.com/api/GetCustomers",
    dataType: 'json',
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data)

      $newData = JSON.parse(data);
      $.each($newData, function(i, v) {
         $('.output').append(v.LastName);
         $('.output').append(v.FirstName);
      });
    }
  });
</script>

 

What am I doing wrong?

Edited by imgrooot
Link to comment
Share on other sites

6 hours ago, Barand said:

$newData = JSON.parse(data);

Try commenting out the above line - it shouldn't be necessary as you specified a data-type: json

I did that. No more error but nothing is displaying in the .output div.

$.each(data, function(i, v) {
  $('.output').append(v.LastName);
});

 

Link to comment
Share on other sites

I have a solution.

Apparently I was inputting the wrong label name. Instead of it being "FirstName", it's actually with lowercase "firstName".

Here's the new code.

<script>
  $.ajax ({
    type: 'GET',
    url: "https://3rdpartywebsite.com/api/GetCustomers",
    dataType: 'json',
    success: function(data) {
      $.each(data, function(i, v) {
         $('.output').append(v.firstName);
         $('.output').append(v.lastName);
      });
    }
  });
</script>

// To access individual record inside the array.
console.log(data[0].firstName);

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.