Joscplan
Joscplan

Reputation: 1034

Using JS to get AJAX data

I have a ajax php file which retrieves a list of data from my database. Now, I need that data loaded with JS into an html.

The data is shown up like this (raw text):

var data=[{"a":"1","b":"Post title1","c":"Category","d":"seo-url"},{"a":"2","b":"Post title2","c":"Category","d":"seo-url"},{"a":"3","b":"Post title3","c":"Category","d":"seo-url"}]

I need that data to be prased and loaded like this in the html file:

<a href="website.com/[seo-url]" title="[Post title]"><p>[Post title]<p>Category: [Category]</a>

How can I do it?

Upvotes: 0

Views: 37

Answers (1)

David
David

Reputation: 1889

Try this

jQuery.each(data, function(index, val) {
    $('#container').append('<a href="website.com/' + val.d + '" title="' + val.b + '"><p>' + val.b + '<p>Category: ' + val.c + '</a>');
});

if you get data from ajax

jQuery.ajax({
    url: 'website.com/ajax/get_data',
    type: 'POST',
    dataType: 'json',
    success: function(data, textStatus, xhr) {
        jQuery.each(data, function(index, val) {
            $('#container').append('<a href="website.com/' + val.d + '" title="' + val.b + '"><p>' + val.b + '<p>Category: ' + val.c + '</a>');
        });
    }
});

replace #container with your selector

Upvotes: 1

Related Questions