0

I would like to add data from a JSON object to HTML markup. I use jQuery and AJAX to read out the data. What I want to achieve is that there will be add for each object in the JSON file a new HTML markup that represent an item.

I use the following code to add the text key from each object.

$.ajax({
    url: 'api/videoData.js',
    dataType: 'json',
    success: function(data) {
        console.log(data); //uncomment this for debug

        for (var i = 0; i < data.content.length; i++) {
            if (data.content[i].type == 'normal') {
                console.log(data.content[i].text);
                $('.article.text').find('p').html(data.content[i].text);
            }
        };
    },
    error: function() { 
        console.log('Houston, we have a problem!');
    }
});

HTML Markup:

<div class="article text">
    <span class="format text alignRight"></span>

    <h4>Subtitle</h4>
    <h3>Title</h3>
    <p>
        Paragraph text
    </p>
</div><!-- End div.article text -->

JSON FILE:

{
    "title":    "London",
    "category": "The Ultimate",
    "image":    "images/content/londen.jpg",
    "website":  "http://www.london.nl/",
    "youtube":  "https://www.youtube.com/watch?v=Sq9rjbouBlY&t=23",
    "maps":     "https://www.google.nl/maps/place/Londen,+Verenigd+Koninkrijk/@51.5114089,-0.1271477,13.79z/data=!4m2!3m1!1s0x47d8a00baf21de75:0x52963a5addd52a99",
    "content":  [
        {
            "type" :        "normal",
            "timeTrigger":  24,
            "title":        "London Eye",
            "subtitle":     "Algemene",
            "picture" :     "images/content/london.jpg",
            "text":         "This is the London Eye",
            "readmore":     "http://wikitravel.org/en/London"
        },{
            "type":         "normal",
            "timeTrigger":  24,
            "title":        "Sherlock Holmes",
            "subtitle":     "Detective",
            "picture" :     "images/content/sherlock_holmes.jpg",
            "text":         "Sherlock Holmes is een fictieve detective  <br> uit de verhalen van de laat-19de-eeuwse",
            "readmore":     "http://nl.wikipedia.org/wiki/Sherlock_Holmes"
        },{
            "type":         "normal",
            "timeTrigger":  39,
            "title":        "Fish \"n Chips",
            "subtitle":     "Eten",
            "picture" :     "images/content/sherlock_holmes.jpg",
            "text":         "Fish and chips is een typisch Britse afhaalmaaltijd .",
            "readmore":     "http://youngandfoodish.com/london/top-10-fish-and-chips-in-london/"
        }
    ]
}

It will console.log all the text of all my objects, but it doesn't appear in my HTML.

7
  • 1
    Your $('.article.text').find('p') selector keeps changing the content of the same element(s), what do you expect? Commented Oct 14, 2015 at 8:08
  • If you showed the structure of your HTML and the receive data we wouldn't have to guess how it looks like. Commented Oct 14, 2015 at 8:08
  • can you show what you are getting as response? Commented Oct 14, 2015 at 8:09
  • 1
    Yeah please show a portion of your HTML & JSON. Commented Oct 14, 2015 at 8:09
  • Use jquery append() in your loop instead of html() Commented Oct 14, 2015 at 8:11

1 Answer 1

1

You should use append instead of html because:

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content.

from the jquery API: API .html()

You can also use jquery each instead of the for loop: API $.each()

Use a markup like these where your articles will be appended:

<div id="articles"></div>

...your ajax:

$.ajax({
        url: 'api/videoData.js',
        dataType: 'json',
        success: function(data) {
            console.log(data); //uncomment this for debug
            Triptube.dataController.timelineEvents(data);

            //the element where the articles should be appended
            var el = $('#articles');

            //empty this element first
            el.empty();

            //you can use jquery each to append all new articles
            $.each(data.content, function(index, value) {
                if (value.type == 'normal') {
                    console.log(value.text);

                    //append every node instead of replacing it with your markup
                    el.append(
                       '<div class="article text">' +
                          '<span class="format text alignRight"></span>' +
                          '<h4>' + value.subtitle + '</h4>' + 
                          '<h3>' + value.title + '</h3>' +
                          '<p>' + value.text + '</p>' +
                       '</div>'
                    );

                }
            });
        },
        error: function() { // Moet deze ook een parameter hebben?
            console.log('Houston, we have a problem!');
        }
});

APIs:

API .empty

API .append()

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for your answer. If I may ask you one more question, how can I do this the best way for also the hole item. SO not only de paragraph, but for each object the code should create or duplicate the basic markup and fill it in with content from my JSON.
Just build your markup as string and let jquery append it as html to your element. So i would do for example: el.append('<div><h3>' + value.title + '</h3><span>' + value.text + '</span></div>').
I've updated my answer with your markup! I named your parent element, where you append your articles markup #articles but that is your choice.
Thank you. I checked it already. One question, index is not used in the function parameter? What does index exactly? Is this needed or?
It is only a possible parameter which is the index of your element in the list (like an array index and you could use it to do something special with the third element for example). There is no need to use it, but it should appear in the declaration of the function. You could alternatively use $.each(function() {}); without any parameters and access your value with $(this).
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.