Sai Manikanta Sai Manikanta - 2 months ago 4
Ajax Question

Load content from another div on same page with on select from dropdown using jQuery/Ajax

I know this is very common question and has multiple solutions already available but I am not able to find a proper solution to the question I had

I have a dropdown list, from where when user select the dropdown, the selection loads a div that is defined in the same page. It works fine, I have implemented it as follows:

<select id="selectMe">
<option value="val1">opt1</option>
<option value="val2">opt2</option>
</select>

<div id="val1" class="group"> content1</div>
<div id="val2" class="group">content2</div>


Jquery::

$(document).ready(function() {
$('.group').hide();
$('#val1').show();
$('#selectMe').change(function() {
$('.group').hide();
$('#' + $(this).val()).show();
})
});


Now, this serves my purpose but takes a lot of time to load the divs as they contain huge data in them (Iframes, external calls) and page is taking lot of time (almost half a minute) to load all the divs before displaying the first div which is pre selected, I am trying to use ajax as I understood that we can dynamically load other divs upon selection instead of loading them all at once on page load, i tried removing documet.ready() with windows.load function, but it didn't work. If i am missing something, can some one please help me out in solving the issue.

Update1:

The code works fine, i donot have any problem with it. I want to load only selected div at once instead of loading all the div's ( About 500) along with the page as it is taking lot of time to load because of huge data (div's -About 500 in number containing Iframe's).

Instead I want to load each div separately dynamically only on selection or restrict load to only fewer number

Update2:

The div contains the data as follows:

<div id="val1" class="group">
<iframe class="DZembed-table" src="//www.datazoa.com/data/table.asp?a=view&th=1A7400B7A3&dzuuid=423&uid=dzadmin" frameborder="0" width="800px" height="270px">Unavailable - Anderson County, Ks - Total Employment (not seasonally adjusted)</iframe>


/* Some text about 10-15 lines */

</div>


I have about 500 in number of such div's

for reference, please visit this page as example and it almost takes the same time to load the page I wanted to change

url: http://kansaseconomy.org/economic-indicators/total-nonfarm-employment-bls

Answer

You have multiple options that don't use <iframe>s. I wouldn't be too concerned about the footprint of your 500 text blocks as they're not super huge.

Option A - JS Store

With this option there's a lot less work when it comes to the markup. You don't have to manually or on the server create 100's of content DIVs. You simply re-use the same DIV.

function createOption( value, text ) {
  
  var opt = document.createElement( 'option' );
  
  opt.value = value;
  opt.text  = text;
  
  return opt;
  
}

function buildSelect( options ) {

  var i    = 0;
  var len  = options.length;
  var frag = document.createDocumentFragment();
  
  for ( ; i < len; i++ ) {    
    frag.appendChild( createOption( i, 'Option ' + ( i + 1 ) ) );
  }
  
  $list.append( frag );
    
}

var data = [
  "Quarter log Blimey hang the jib Davy Jones' Locker tackle boatswain squiffy. Shrouds American Main scallywag wench Blimey furl ye fathom. Holystone keel Pieces of Eight topsail come about Gold Road blow the man down fore. Overhaul mizzen gunwalls black jack long clothes weigh anchor fluke code of conduct. Take a caulk black spot brig fire ship gun long clothes jury mast tender. Ye yardarm to go on account jury mast grog blossom Plate Fleet broadside grog. Scuttle chandler belaying pin pirate gaff hulk pressgang Spanish Main. Topmast chantey crimp yardarm flogging jib line avast. Warp Chain Shot shrouds rum flogging fire ship grapple log. Take a caulk rope's end Plate Fleet log haul wind Blimey keelhaul overhaul.",
  "Port parrel cog chase Brethren of the Coast scourge of the seven seas pink American Main spike ho. Ahoy Buccaneer Shiver me timbers provost Arr bring a spring upon her cable blow the man down line pillage hempen halter. Provost Letter of Marque code of conduct Sea Legs strike colors scallywag long clothes heave to measured fer yer chains pressgang. Run a rig gabion cackle fruit marooned sutler jolly boat Jolly Roger jib belaying pin killick. Fire ship gally weigh anchor lugsail gun tack league Barbary Coast spyglass Privateer. Spanker killick grog clipper jib dead men tell no tales marooned barque prow grapple. Fore Brethren of the Coast hail-shot poop deck keel boom run a rig line Shiver me timbers splice the main brace. ",
  "Nelsons folly hulk strike colors lass six pounders bring a spring upon her cable gabion jolly boat. Man-of-war nipper to go on account main sheet scuppers crack Jennys tea cup doubloon Nelsons folly. Barque quarter Jolly Roger jib tender lee brig avast. Transom draft draught scallywag flogging coxswain hail-shot booty. Coffer scurvy grog crack Jennys tea cup grapple provost Plate Fleet ho. Black spot knave draught Shiver me timbers topgallant rum brigantine gaff. Hardtack overhaul Gold Road stern fire ship run a rig haul wind aft. Execution dock parley provost skysail haul wind heave down barque sloop. Plunder grog sloop smartly weigh anchor Pieces of Eight hands bilge. Scallywag keelhaul reef pillage tackle skysail salmagundi man-of-war."
];

var $list = $( '#list' );
var $display = $( '#display' );

$list.on( 'change', function ( e ) {
  $display.text( data[ this.value ] );
} );

// Insert default.
$display.text( data[ 0 ] );

buildSelect( data );
#display {
  margin: 2rem 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="list"></select>
<div id="display"></div>

Option B - Store in HTML

Here you need to manually or with the help of a server side language build 100's of DIVs, including their IDs. Which, if doing manually could be a real pain.

var $list = $( '#list' );
var $options = $( '.option' );

$list.on( 'change', function ( e ) {
  
  $options.hide();
  $( '#option-' + this.value ).show();
  
} );
.option {
  display: none;
  margin: 2rem 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="list">
  <option value="0">Option 1</option>
  <option value="1">Option 2</option>
  <option value="2">Option 3</option>
</select>

<div id="option-0" class="option" style="display: block;">
  Quarter log Blimey hang the jib Davy Jones' Locker tackle boatswain squiffy. Shrouds American Main scallywag wench Blimey furl ye fathom. Holystone keel Pieces of Eight topsail come about Gold Road blow the man down fore. Overhaul mizzen gunwalls black jack long clothes weigh anchor fluke code of conduct. Take a caulk black spot brig fire ship gun long clothes jury mast tender. Ye yardarm to go on account jury mast grog blossom Plate Fleet broadside grog. Scuttle chandler belaying pin pirate gaff hulk pressgang Spanish Main. Topmast chantey crimp yardarm flogging jib line avast. Warp Chain Shot shrouds rum flogging fire ship grapple log. Take a caulk rope's end Plate Fleet log haul wind Blimey keelhaul overhaul.
</div>
<div id="option-1" class="option">
  Port parrel cog chase Brethren of the Coast scourge of the seven seas pink American Main spike ho. Ahoy Buccaneer Shiver me timbers provost Arr bring a spring upon her cable blow the man down line pillage hempen halter. Provost Letter of Marque code of conduct Sea Legs strike colors scallywag long clothes heave to measured fer yer chains pressgang. Run a rig gabion cackle fruit marooned sutler jolly boat Jolly Roger jib belaying pin killick. Fire ship gally weigh anchor lugsail gun tack league Barbary Coast spyglass Privateer. Spanker killick grog clipper jib dead men tell no tales marooned barque prow grapple. Fore Brethren of the Coast hail-shot poop deck keel boom run a rig line Shiver me timbers splice the main brace.
</div>
<div id="option-2" class="option">
  Nelsons folly hulk strike colors lass six pounders bring a spring upon her cable gabion jolly boat. Man-of-war nipper to go on account main sheet scuppers crack Jennys tea cup doubloon Nelsons folly. Barque quarter Jolly Roger jib tender lee brig avast. Transom draft draught scallywag flogging coxswain hail-shot booty. Coffer scurvy grog crack Jennys tea cup grapple provost Plate Fleet ho. Black spot knave draught Shiver me timbers topgallant rum brigantine gaff. Hardtack overhaul Gold Road stern fire ship run a rig haul wind aft. Execution dock parley provost skysail haul wind heave down barque sloop. Plunder grog sloop smartly weigh anchor Pieces of Eight hands bilge. Scallywag keelhaul reef pillage tackle skysail salmagundi man-of-war.
</div>

One modification you could make to this approach is to keep all .option DIVs hidden and to copy to contents of the target DIV to a "display" DIV like I have done in the other examples. Then you don't need to hide() and show() the .option DIVs.

Option C - Ajax with JS Cache

Below is some pseudo code that has not been tested but should give you an idea of how to setup AJAX (front-end portion) if you really wanted.

<select id="list">
   <option value="0" selected>Option 1</option>
   <option value="1">Option 2</option>
   <!-- to 500 -->
   <option value="499">Option 3</option>
</select>

<!-- Insert Default option. -->
<div id="display">
    Quarter log Blimey hang the jib Davy Jones' Locker tackle boatswain squiffy. Shrouds American Main scallywag wench Blimey furl ye fathom. Holystone keel Pieces of Eight topsail come about Gold Road blow the man down fore. Overhaul mizzen gunwalls black jack long clothes weigh anchor fluke code of conduct. Take a caulk black spot brig fire ship gun long clothes jury mast tender. Ye yardarm to go on account jury mast grog blossom Plate Fleet broadside grog. Scuttle chandler belaying pin pirate gaff hulk pressgang Spanish Main. Topmast chantey crimp yardarm flogging jib line avast. Warp Chain Shot shrouds rum flogging fire ship grapple log. Take a caulk rope's end Plate Fleet log haul wind Blimey keelhaul overhaul.
</div>
var cache    = {};
var $list    = $( '#list' );
var $display = $( '#display' );

// Append text to display DIV.
function appendText( value ) {
  $display.text( value );
}

// Get text via AJAX.
function getText( opt_id ) {

  var jqxhr = $.ajax( {
    url: '/your/endpoint/',
    data: { id: opt_id },
    method: 'POST'
  } );

  jqxhr.done( function ( data, status , xhr ) {

    // Cache for future use.
    cache[ opt_id ] = data;

    appendText( data );

  } );
  jqxhr.fail( function () {} ); // Handle request failure.
  jqxhr.always( function () {} ); // Run on success or error.

}

$list.on( 'change', function ( e ) {

  if ( cache[ this.value ] ) {
    appendText( cache[ this.value ] );
  } else {
    getText( this.value );
  }

} );

Reference: jQuery.ajax()

Personally I'd go for option A and then B unless there are some other overriding concerns that I'm not aware of.

Comments