Aadi Droid
Aadi Droid

Reputation: 1739

How to show results in div and then async update them

I created a web service that helps query wikipedia pages, a different kind of search. My search service returns page links to me. I am able to retrieve this and display it in a div. My question is, how do I show the links as soon as they arrive and then do an async call to wikipedia to fetch a thumbnail and basic description of the page and replace the earlier posted result with the formatted thumbnail and description.

For example, twitter does this

<blockquote class="twitter-tweet">
  <p>Loading tweet ' + tweet.id  + '</p>
  <a href="https://twitter.com/'+ tweet.uname + '/status/' + tweet.id +'"></a>
</blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8">
</script>

Doing this first shows only the tweet id on the page and then once it hears back from twitter it makes it an embedded tweet.

Upvotes: 3

Views: 151

Answers (1)

brother Filip
brother Filip

Reputation: 111

For every url from the result returned by your service:

  1. show the url (wrapped in HTML element)
  2. request for details and update the element when the details arrive

Semi pseudocode example:

// query your service and get article urls
$.getJSON(web_service_url, { // AJAX call
        query: query
    }, function(response) {
        // reset search results
        $('#results').html('');

        // iterate through article urls and for each url...
        $.each(response.urls, function(i, url) {
                // 1.) show it
                var item_element = $('#results').append('<div>' + url + '</div>');

                // 2.) query wikipedia for details...
                $.getJSON(wikipedia_article_details_url, { // AJAX call
                    url: url
                }, function(response) {
                    // 2.1) and replace the url with the details when they arrive
                    item_element.html(response.details);
                });
            }
        });

Upvotes: 1

Related Questions