Search code examples
jqueryajaxwordpresswordpress-rest-api

I am trying to use the wordpress rest api but data does not display


I am just starting with the Wordpress rest API and I am trying to integrate it into a mobile app. I have imported jquery and the url is good and displays the data in a browser.

Here is my code so far, I can not get the data to display

<body>

    <script>
   $.ajax({
    type: 'GET',
    url: 'http://wpecom.robbotdev.com/blog/wp-json/' + 'wp/v2/posts',
    dataType: 'json',
    success: function(data){
    // do something with the data here
        $.each(data, function(index, value) {

  $('ul.topcoat-list').append('<li class="topcoat-list__item">' +
    '<img src="'+value.featured_image.attachment_meta.sizes.medium.url+'" /><br>' +
    '<h3>'+value.title+'</h3>' +
    '<p>'+value.content+'</p></li>');

});
    }
});

    </script>

    <li class="topcoat-list__item">
<img src="http://url.com/featured/image.png" /><br>
<h3>Title</h3>
<p>Post excerpt</p>
</li>

</body>

Solution

  • When I use AJAX for this, I don't use type or dataType. Try removing those two and see if it works out! Also, are there any JS errors in your console? Maybe the AJAX is running before the ul.topcoat-list is even created. Maybe put your AJAX call inside a jQuery( document ).ready( function(), or move it below the HTML before the </body>.