Search code examples
jqueryjquery-ui-tabs

jquery Tabs with ajaxOptions


Scratching my head on this one. With jQuery tabs I am attempting to use ajaxOptions to post data to the page before I load it.

So I have a form on the page before my tabs with some input fields. ie,

<form id="myform" method="post">
<!-- inputs etc -->
</form>

Then my tabs

<div id="tabs">
  <ul>
    <li><a href="#tabs-1">Preloaded</a></li>
    <li><a href="ajax/content1.html">Tab 1</a></li>
  </ul>

  <div id="tabs-1">
    <p>Initital content</p>
  </div>
</div>

ok so now I should be able to serialize my form so when click a tab it should be a post request ie,

$( "#tabs" ).tabs({
    ajaxOptions: {
        type: 'post',
        data: $("#myform").serialize(),
        error: function( xhr, status, index, anchor ) {
            $( anchor.hash ).html(
            "Couldn't load this tab. We'll try to fix this as soon as possible. " +
            "If this wouldn't be a demo." );
        }
    }
});

It does perform the post request but the form data is always empty.

Any ideas why?

Thanks

Lee


Solution

  • Since this runs when you first create the tabs:

    data: $("#myform").serialize(),
    

    The data is whatever it was then, it's never updated. The easiest solution here is just to update that data when it's needed, by using the tab's select event, like this:

    $( "#tabs" ).tabs({
      select: function() {
        $(this).tabs("option", { ajaxOptions: { data: $("#myform").serialize() } });
      },
      ajaxOptions: {
        type: 'post',
        error: function( xhr, status, index, anchor ) {
          $( anchor.hash ).html(
            "Couldn't load this tab. We'll try to fix this as soon as possible. " +
            "If this wouldn't be a demo." );
        }
      }
    });
    

    You can test it out here, just look in Firebug, etc to see the form data is being updated and sent with each tab AJAX request.