<rss version="2.0" xmlns:a10="http://www.w3.org/2005/Atom"><channel><title>abrie.net feed</title><link>http://abrie.net/code.aspx</link><description>This is a feed for code articles on abrie.net</description><managingEditor>abrie@abrie.net</managingEditor><category>sandbox</category><item><guid isPermaLink="false">1002</guid><link>http://abrie.net/code.aspx#1002</link><title>Twitter search with template binding</title><description>&lt;p&gt;In this article I wanted to be able to load a JSON object and then bind that to html like a repeater control would do in ASP. I decided that real time updating of twitter search results would be a nice way to demonstrate this. &lt;/p&gt; </description><a10:updated>2011-11-02T08:01:51-05:00</a10:updated><a10:content type="html">&lt;p&gt;I wanted to be able to load a JSON object and then bind that to html like a repeater control would do in ASP. I decided that real time updating of twitter search results would be a nice way to demonstrate this. There are a few javascript templating engines out there, but I decided to use the one that Microsoft contributed to jQuery as outlined &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/05/07/jquery-templates-and-data-linking-and-microsoft-contributing-to-jquery.aspx"&gt;here&lt;/a&gt;.&lt;br /&gt;In the head of the html load the templating library.&lt;/p&gt; 
&lt;pre class="brush: js"&gt;&amp;lt;script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt; 

&lt;p&gt;We have a text box for our search term and a button to call the javascript function and lastly a div with Id &lt;i&gt;results&lt;/i&gt; where we will append and remove the tweets.&lt;/p&gt;
&lt;pre class="brush: xml"&gt;&amp;lt;div&amp;gt;
     &amp;lt;input type="text" id="search" placeholder="Search Term" /&amp;gt;
     &amp;lt;input type="button" id="load" value="load" onclick="refresh();" /&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;br /&amp;gt;
&amp;lt;div id="results"&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;Because we don't want to rebuild our html markup everytime we will bind the markup on page load. So once the page has been loaded we call our binding function&lt;/p&gt; 

&lt;pre class="brush: js"&gt;
         $(document).ready(function () {
             loadMarkup();
         });
&lt;/pre&gt;

&lt;p&gt;In &lt;i&gt;loadMarkup&lt;/i&gt; we do a basic GET to the server to retrieve our html markup and bind it to a template, &lt;i&gt;tweetTemplate&lt;/i&gt; in this case.&lt;/p&gt;

&lt;pre class="brush: js"&gt;function loadMarkup() {
     $.get('/assets/views/tweet.html', function (markup) {
         $.template("tweetTemplate", markup);
     });
}&lt;/pre&gt;

&lt;p&gt;In the html markup we received from the server we need to bind to properties of the JSON object. For example when receiving results from the twitter API the JSON object has a &lt;i&gt;text&lt;/i&gt; property which contains the text of the tweet. In the html markup we bind to these properties using a ${} selector, eg. ${text}. Here is the complete markup as used in the demo.&lt;/p&gt;

&lt;pre class="brush: xml"&gt;&amp;lt;div class="tweet"&amp;gt;
    &amp;lt;div class="table"&amp;gt;
        &amp;lt;div class="row"&amp;gt;
            &amp;lt;div class="cell"&amp;gt;
                &amp;lt;img alt="pic" src="${profile_image_url}" title=" ${from_user}" /&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class="cell"&amp;gt;
                ${text}
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;div&amp;gt;
        &amp;lt;strong&amp;gt;${from_user}&amp;lt;/strong&amp;gt;
        &amp;lt;div style="text-align: right;" &amp;gt;${created_at}&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;Now we can have a look at the repeating search function. We start off by html encoding our search string and setting our url. Note that &lt;i&gt;last_id&lt;/i&gt; is a variable that is intialized as 0.&lt;/p&gt;

&lt;pre class="brush: js"&gt;var query = escape($('#search').val());

var url = 'http://search.twitter.com/search.json?q=';
var options = '&amp;result_type=recent&amp;rpp=5&amp;callback=?&amp;since_id=' + last_id;&lt;/pre&gt; 

&lt;p&gt;We do a GET to the twitter API to retrieve our JSON object. We store the last Id we searched as this allows us to only search from that point next time. Now we bind our data to our template &lt;i&gt;tweetTemplate&lt;/i&gt; and add this to the &lt;i&gt;results&lt;/i&gt; div with a fade in.&lt;/p&gt;

&lt;pre class="brush: js"&gt;
$.getJSON(url + query + options, function (json) {
   last_id = json.max_id_str;
   $.tmpl("tweetTemplate", json.results).prependTo("#results").hide().fadeIn(2000);
});&lt;/pre&gt; 

&lt;p&gt;To make sure the div doesn't grow to an infinite size I remove all children from &lt;i&gt;results&lt;/i&gt; until there is only 8 tweets left.&lt;/p&gt;

&lt;pre class="brush: js"&gt;while ($('#results').children().size() &gt; 8) {
        var last = $('#results').children().last().remove();
    }&lt;/pre&gt; 

&lt;p&gt;Finally we set the function to be called again in 2 seconds.&lt;/p&gt;

&lt;pre class="brush: js"&gt;t = setTimeout("refresh()", 2000);&lt;/pre&gt; 

&lt;p&gt;Here is the complete function.&lt;/p&gt;
&lt;pre class="brush: js"&gt;function refresh() {
    var query = escape($('#search').val());

    var url = 'http://search.twitter.com/search.json?q=';
    var options = '&amp;result_type=recent&amp;rpp=5&amp;callback=?&amp;since_id=' + last_id;

    $.getJSON(url + query + options, function (json) {
        last_id = json.max_id_str;
        $.tmpl("tweetTemplate", json.results).prependTo("#results").hide().fadeIn(2000);
    });
    while ($('#results').children().size() &gt; 8) {
        var last = $('#results').children().last().remove();
    }
    t = setTimeout("refresh()", 2000);
}&lt;/pre&gt; 
&lt;p&gt;If you have any questions drop me a mail.&lt;/p&gt;</a10:content></item><item><guid isPermaLink="false">1001</guid><link>http://abrie.net/code.aspx#1001</link><title>Post to JSON service</title><description>&lt;p&gt;Welcome to my first post on my site. &lt;br /&gt;What I want to achieve today is to do an empty ajax post using jQuery to a test method I have running on my WCF service.&lt;/p&gt;</description><a10:updated>2011-11-02T08:01:22-05:00</a10:updated><a10:content type="html">&lt;p&gt;Welcome to my first post on my site. &lt;br /&gt;What I want to achieve today is to do an empty ajax post using jQuery to a test method I have running on my WCF service.
What we want is a button that will do the ajax post in javascript as well as a div to write our result to. Here is the html:&lt;/p&gt;

&lt;pre class="brush: xml"&gt;&amp;lt;input type="button" value="Test" onclick="testClick();" /&amp;gt;
    &amp;lt;div id="result"&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;So now we have a button that calls &lt;i&gt;testClick&lt;/i&gt; as well as our div to append the results to. Next we need to write the javascript function. Here is the full function:&lt;/p&gt;
&lt;pre class="brush: js"&gt;function testClick() {
    $('#result').empty();
    $.ajax({
        type: "POST",
        url: '/WCF/Dataservice.svc/test',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            $('#result').append('service is up');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $('#result').append(textStatus + ' / ' + errorThrown);
        }
    });
}&lt;/pre&gt;
&lt;p&gt;The first thing we want do when entering the function is to clear the div of previous results. We use the jQuery selector to select the div with an id of &lt;i&gt;result&lt;/i&gt; and then empty the div.&lt;/p&gt;

&lt;pre class="brush: js"&gt;$('#result').empty();&lt;/pre&gt;

&lt;p&gt;Now we do the ajax post, by using the jQuery &lt;i&gt;$.ajax&lt;/i&gt; function and setting the type to &lt;i&gt;POST&lt;/i&gt;.&lt;/p&gt;

&lt;pre class="brush: js"&gt;$.ajax({
        type: "POST",&lt;/pre&gt;

&lt;p&gt;After this set the URL of the service and the content type. In this case I am setting it to JSON, but you can use any type as long as the service support it.&lt;/p&gt;

&lt;pre class="brush: js"&gt;url: '/WCF/Dataservice.svc/test',
        contentType: "application/json; charset=utf-8",&lt;/pre&gt;

&lt;p&gt;Lastly we define what to do when the service call is finished. When the ajax call has completed successfully we select the &lt;i&gt;result&lt;/i&gt; div again and append some text to indicate that the service call completed.&lt;/p&gt;

&lt;pre class="brush: js"&gt;success: function (data) {
            $('#result').append('service is up');
        },&lt;/pre&gt;
&lt;p&gt;In case of an error we select the &lt;i&gt;result&lt;/i&gt; div as well and append the error message.&lt;/p&gt;

&lt;pre class="brush: js"&gt;
        error: function (jqXHR, textStatus, errorThrown) {
            $('#result').append(textStatus + ' / ' + errorThrown);
        }
    });&lt;/pre&gt;

&lt;p&gt;So now you should be able to do a basic ajax post. Drop me a mail if you have any questions.&lt;/p&gt;</a10:content></item></channel></rss>
