Citizen SP
Citizen SP

Reputation: 1411

Load items with ajax in div's

I'm currently using the following javascript to load items in a a few div's:

<script>
    $.ajax({
        url: 'load.php?type=divA',
        cache: false,     
        success: function(data){
        $('#divA').html(data); 
        }
    });   
    $.ajax({
        url: 'load.php?type=divB',
        cache: false,     
        success: function(data){
        $('#divB').html(data); 
        }
    });  </script>

HTML:

<div id="divA">
<!-- Load divA item here -->
</div>
<div id="divB">
<!-- Load divB item here -->
</div>

I'm looking (and think) there's a better way to do this. Similar to this: 1 function for a div's, which automatically loads the items in (multiply) div's:

function loadItem(<DIV ID>) {
 $.ajax({
            url: 'load.php?type=<DIV ID>',
            cache: false,     
            success: function(data){
            $('<DIV ID>').html(data); 
            }
        }); 
};

Upvotes: 0

Views: 209

Answers (2)

Jai
Jai

Reputation: 74738

I think this is better:

function loadItem(div) {
   $.ajax({
      url: 'load.php?type='+div,
      cache: false,     
      success: function(data){
         $('#'+div).html(data); 
      }
   }); 
};

$(function(){
   $('div[id^="div"]').each(function(){
      loadItem(this.id);
   });
});

What this code is doing:

  1. make a global function putting function outside of doc ready.
  2. In the doc ready block loop through the div whose id starts with div and pass that id to the function.
  3. So if there are two divs then there will be two ajax calls.

This is a late reply:

$('div[class*="div"]').each(function(){ // class contains div
   loadItem(this.className.split(' ')[1]); 
});// split by ' ' space and pass the second index as arrays are 0 based index.

Upvotes: 1

keune
keune

Reputation: 5795

It can be done like this:

function loadItem(divId) {
    $.ajax({
        url: 'load.php?type=' + divId,
        cache: false,
        success: function (data) {
            $('#' + divId).html(data);
        }
    });
};

Upvotes: 1

Related Questions