Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading JSON-encoded AJAX content into jQuery UI tabs

We want all of our AJAX calls in our web app to receive JSON-encoded content. In most places this is already done (e.g. in modals) and works fine.

However, when using jQueryUI's tabs (http://jqueryui.com/demos/tabs/) and their ajax functionality, only plaintext HTML can be returned (i.e. from the URLs specified in the a tags below). How do I get the tab function to recognize that on each tab's click, it will be receiving JSON-encoded data from the specified URL, and to load in the .content index of that JSON?

$(function() {
    $('div#myTabs').tabs();     
});

<div id="mytabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all">
    <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
        <li class="ui-state-default ui-corner-top"><a href="/url/one">Tab one</a></li>
        <li class="ui-state-default ui-corner-top"><a href="/url/two">Tab two</a></li>
    </ul>
</div>
like image 283
pocketfullofcheese Avatar asked May 07 '10 01:05

pocketfullofcheese


2 Answers

You can use the dataFilter option of the ajax call to convert your json response to the html you want to be inserted in to the panel of the tab.

Something like this:

$('#mytabs').tabs({
    ajaxOptions: {
        dataFilter: function(result){
            var data = $.parseJSON(result);
            return data.myhtml;
        }
    },
}); 

If you JSON response looked like this:

{"myhtml":"<h1>hello<\/h1>"}
like image 170
PetersenDidIt Avatar answered Sep 28 '22 04:09

PetersenDidIt


I had to add:

this.dataTypes=['html']

to get this to work.

In context:

      ,ajaxOptions: {
    dataFilter: function(result,type){
      var data = $.parseJSON(result);
       // Trick jquery to think that it's html
       this.dataTypes=['html']
       return '<p>'+data.credential.id+'</p>';
    }
    ,error: function( xhr, status, index, anchor ) {
      $( anchor.hash ).html( i18n.AJAXError + ' (' + status + ')' );
    }
  }
like image 27
ajf Avatar answered Sep 28 '22 05:09

ajf