Load content depending on the device using an ajax call in Drupal 7

This tutorial explains how to load "device specific content" depending on the device being used.

For this example the content being used are two embed views, one is called "Mobile embed" and the other is called "Desktop embed". To see how to create an embed view please go to the previous tutorial: Embeding a view in Drupal 7

1. Detecting the device and retrieving the content using an ajax call

Detecting the device must be done in javascript as it is executed on the client side. There are various ways of detecting the device being used, here is just one way of doing so. The ajax call has the device as a parameter and in PHP the content will be loaded depending on it.

var device = 'desktop';
if( /Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent) ) {
   device = 'mobile';
}
var url = '/ajax/load_device/' + device;

2. Loading the content

The content is loaded in PHP on the server side. In this example the views_embed_view() function is used to load an embed view. The machine name of the two embed views used in this example are "embed_mobile" and "embed_desktop".

<?php
/**
* Implementation of hook_block_menu().
*/
function mymodule_menu() {
 
$items['ajax/load_device'] = array(
   
'page callback' => 'mymodule_loadblock',
   
'type' => MENU_CALLBACK,
   
'access arguments' => array('access content'),
  );
  return
$items;
}
?>

and the callback function:

<?php
function mymodule_loadblock($device = 'mobile') {
  if(
$device == 'mobile') {
   
$html = views_embed_view('myview', "embed_mobile");
  } elseif (
$device == 'desktop') {
   
$html = views_embed_view('myview', "embed_desktop");
  }
 
$result = array(
   
'status' => 'ok',
   
'html' => $html,
  );
 
drupal_json_output($result);
}
?>

3. Appending the content to a DOM element

Now that the content is loaded it needs to be appended to an element in the html. Any class or id will work however in this example things are going to be complicated a little to show a very useful trick which will allow to append the content to a block. The advantage of this is that the block may be moved to different regions using the block administration which is much more user friendly than hard coding it in PHP in a template file. 

3.1 Creating the block

<?php
/**
* Implementation of hook_block_info().
*/
function mymodule_block_info() {
 
$blocks[0] = array(
   
'info' => t('Main'),
  );
  return
$blocks;
}

/**
* Implementation of hook_block_view().
*/
function mymodule_block_view($delta='') {
 
$block = array();
  switch (
$delta) {
    case
0:
     
$block['subject'] = t('<none>');
     
$block['content'] = theme('mymodule_main');
      break;
  }
  return
$block;
}

/**
* Implements hook_theme().
*/
function mymodule_theme() {
  return array(
   
'mymodule_main' => array(
     
'template' => 'templates/main',
    ),
  );
}
?>

and the file main.tpl.php which should be located in the template/ directory of the module "mymodule".

<div id="main-block">
  <div id="inner-data">
  </div>
</div>

3.2 Appending the content to the block

The content loaded needs to be appended to the block #id. 

  $.get(url, function(data) {
    if (data.html) {
      $("#main-block").html(data.html);
    }
  });

and here is all the javascript together:

(function ($) {

$(function() {
  var device = 'desktop';
  if( /Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent) )
  {
     device = 'mobile';
  }
  var url = '/ajax/load_device/' + device;
  $.get(url, function(data) {
    if (data.html) {
      $("#main-block").html(data.html);
    }
  });
});
})(jQuery);

Comments

4

Cool technique, but since it is ajax, it shouldn't be used for SEO-critical elements. Google just doesn't see any ajax loaded content.

How about loading a text only view on page view and replace it with a rich view by ajax? Wouldn't hurt SEO then, right?

I think that by placing the contents of the view in a <noscript> it will work fine for the Web bots

cheap michael kors,http://www.cheapmichaelkors.us.org/ nike shoes,http://www.cheap-nikeshoes.net/ cheap oakley sunglasses,http://www.cheapoakley.us.org/ cheap oakley ,http://www.cheapoakleysunglasses.ar.com/ cheap oakley sunglasses,http://www.cheap-oakleysunglasses.in.net/ cheap ray ban,http://www.cheaprayban.com.co/ boots on sale,http://www.cheapshoes.com.co/ cheap ugg boots,http://www.cheapuggboots.eu.com/ flat iron,http://www.chiflatiron.net.co/ christian louboutin,http://www.christian--louboutin.in.net/ louboutin shoes,http://www.christianlouboutin.org.uk/ christian louboutin shoes,http://www.christianlouboutinshoes.jp.net/ coach outlet online,http://www.coachfactory-outlet.co.com/ burberry,http://www.burberry--outlet.in.net/ burberry outlet,http://www.burberryoutlet.me.uk/ burberry factory,http://www.burberryoutlet.club/ burberry,http://www.burberryoutlet-online.in.net/ cheap calvin kleins,http://www.calvinklein.co.com/ celine handbags,http://www.celinebags.org/ chanel handbags,http://www.chanelhandbags.net.in/ easton bats,http://www.cheap-baseballbats.net/ christian louboutin shoes,http://www.christianlouboutinshoes.ar.com/ nfl jerseys,http://www.cheap-jerseys.us.org/ cheap jordans,http://www.cheap-jordans.net/ coach factory,http://www.coachfactory-outlet-online.in.net/ coach outlet usa,http://www.coach-handbags.com.co/ designer handbags,http://www.handbagsoutlet.com.co/ tommy hilfiger,http://www.hilfigeroutlet.in.net/ ed hardy,http://www.edhardy.in.net/ levi's jeans,http://www.levisjeans.com.co/ bcbg max,http://www.bcbgdresses.net/ bebe dresses,http://www.bebeclothing.net/ harrods,http://www.harrods-london.co.uk/ gucci outlet,http://www.guccishoes.com.co/ ralph lauren outlet online,http://www.ralphlaurenoutletonline.us.org/ lululemon,http://www.lululemoncanada.ca/ yoga pants,http://www.yoga-pants.ca/ nike canada,http://www.nike-shoes-canada.ca/ pandora,http://www.pandora-charms-canada.ca/ watches,http://www.rolex-watches-canada.ca/ michael kors,http://www.michael-kors-canada-outlet.ca/ adidas,http://www.adidas--canada.ca/ tiffany,http://www.tiffanyandco-canada.ca/ hollister,http://www.hollistercanada.ca/ abercrombie and fitch,http://www.abercrombie-and-fitch.ca/ oakley,http://www.oakley-sunglasses-canada.ca/ wedding dresses,http://www.wedding--dresses.ca/ swarovski,http://www.swarovskicanada.ca/ hilfiger,http://www.tommy-hilfiger-canada.ca/ new balance,http://www.new-balance.ca/ burberry,http://www.burberrycanada.ca/ north face,http://www.the-north-face.ca/ ralph lauren,http://www.ralph-lauren.ca/ ray ban,http://www.ray--ban.ca/ coach outlet,http://www.coachoutlet-online.com.co/ coach store online,http://www.coachoutletstore.net.co/ coach outlet,http://www.coachoutletstore-online.com.co/ chanel sunglasses,http://www.coco-chanelbags.com.co/ converse shoes,http://www.converse.net.co/ coach handbags,http://www.designerhandbagsoutlet.com.co/ eyeglasses online,http://www.eyeglassesonline.us.org/ eyeglass frames,http://www.eyeglassframes.us.org/ burberry clothes,http://www.fashion-clothing.us.org/ salvatore ferragamo,http://www.ferragamo.com.co/ burberry outlet,http://burberry.outletnow.org/ christian louboutin outlet,http://christianlouboutin.outlet-shoes.net/ tory burch sandals,http://toryburch.salesandals.net/ abercrombie and fitch,http://www.abercrombieand-fitch.com.co/ abercrombie and fitch,http://www.abercrombiefitch.us.com/ abercrombie,http://www.abercrombie-kids.us.com/ nike huarache,http://www.air-huarache.co.uk/ air jordan,http://www.airjordans.us/ air jordan shoes,http://www.airjordanshoes2015.com/ nike air max 2015,http://www.airmax-2015.org/ air max,http://www.airmax-90.org/ babyliss pro,http://www.babylisspro.in.net/ basketball shoes,http://www.basketballshoes.com.co/ beats by dre outlet,http://www.beatsbydrdre.co.com/ beats by dre,http://www.beatsbydre.com.co/ monster beats outlet,http://www.beats-by-dre.com.co/ beats headphones,http://www.beatsheadphones.in.net/ bottega,http://www.bottega.us/ burberry outlet online,http://www.burberry-handbags.in.net/ ferragamo shoes,http://www.ferragamoshoes.net/ hair straightener,http://www.ghdhairstraightener.com.co/ gucci shoes outlet,http://www.gucci-uk.me.uk/ gucci handbags,http://www.guccihandbags.net.co/ gucci factory,http://www.guccioutletsale.in.net/ gucci outlet,http://www.gucci-outlet.biz/ gucci shoes,http://www.guccishoes.in.net/ gucci shoes,http://www.guccishoes.us.org/ hermes,http://www.hermesbags.club/ hermes birkin,http://www.hermesbirkin.biz/ hermes outlet online,http://www.hermesoutlet.top/ hollister,http://www.hollister.us.org/ hollister clothing,http://www.hollisterclothing-store.in.net/ insanity workout,http://www.insanityworkout.net.co/ iphone cases,http://www.iphone-cases.us/ jimmy choo,http://www.jimmychoo.net.co/ jordan retro,http://www.jordanretro.org/ jordan shoes,http://www.jordan-shoes.com.co/ juicy couture outlet,http://www.juicycouture.com.co/ juicy couture handbags,http://www.juicycoutureoutlet.net.co/ kate spade,http://www.kate-spade.com.co/ kate spade handbags,http://www.katespade-outlet.com.co/ kate spade outlet online,http://www.kate-spades.com/ longchamp,http://www.longchamp.us.org/ longchamp handbags,http://www.longchamp.com.co/ louboutin,http://www.louboutin.jp.net/ louis vuitton canada,http://www.louis-vuittoncanada.ca/ louis vuitton bags,http://www.louisvuitton.jp.net/ louis vuitton,http://www.louis--vuitton.org.uk/ vuitton handbags,http://www.louisvuitton.so/ louis vuitton outlet online,http://www.louisvuittonas.com/ louis vuitton,http://www.louisvuitton-outlet.com.co/ louis vuitton,http://www.louisvuitton-outlets.us/ marc jacobs handbags,http://www.marcjacobsonsale.com/ mcm bags,http://www.mcmbags.in.net/ mcm backpack,http://www.mcmhandbags.com.co/ michael kors,http://www.michaelkors.so/ cheap michael kors,http://www.michael--kors.us.com/ michael kors bags sale,http://www.michaelkorsbags.us.org/ michael kors,http://www.michaelkorshandbags.org.uk/ michael kors outlet online,http://www.michael-kors-handbags.us.com/ michael kors outlet,http://www.michaelkorsoutlet.ar.com/ michael kors outlet,http://www.michael-kors-outlet.us.org/ michael kors outlet online,http://www.michaelkorsoutlet-online.ar.com/ michael kors outlet online sale,http://www.michael-kors-outlet-online.us.org/ michael kors outlet store,http://www.michaelkorsoutletonline-sale.us.com/ michael kors uk,http://www.michaelkors-uk.org.uk/ mont blanc pens,http://www.montblanc-pens.in.net/ new balance,http://www.newbalance-outlet.org/ nike air max,http://www.nike-air-max.us/ nike factory,http://www.nikefactory.org/ nike free,http://www.nikefree5.net/ nike free run,http://www.nikefree-run.net/ nike free,http://www.nikefree-run.org.uk/ air jordans,http://www.jordanrelease-dates.net/ nike mercurial,http://www.nikemercurial.in.net/ nike roshe,http://www.nikerosherun.us/ nike outlet store,http://www.nikestore.us/ north face,http://www.northface.us.org/ north face clearance,http://www.northfaceoutlet.com.co/ oakley outlet,http://www.oakleyoutlet.us.org/ oakley sunglasses,http://www.oakleysunglasses.gr.com/ oakley sunglasses cheap,http://www.oakleysunglassescheap.in.net/ oakley sunglasses,http://www.oakley-sunglasses.top/ omega watches,http://www.omegawatches.us.com/ pandora charms,http://www.pandora-charms.org.uk/ pandora jewelry,http://www.pandorajewelry.top/ polo outlet,http://www.polo-outlets.com/ prada outlet,http://www.pradahandbags.net.co/ prada handbags,http://www.pradahandbags.com.co/ prada outlet,http://www.pradashoes.com.co/ ralph lauren uk,http://www.ralph-lauren.org.uk/ polo ralph lauren outlet,http://www.ralphlaurenoutlet.us.com/ ralph lauren,http://www.ralphlauren-outlet.org.uk/ ralph lauren shirts,http://www.ralphlaurenoutletonline.com.co/ ralph lauren outlet,http://www.ralphlaurenoutletonline.in.net/ polo ralph lauren,http://www.ralphlaurenpolo.in.net/ ray ban outlet,http://www.ray-ban-outlet.us.com/ ray bans,http://www.raybans.us.org/ ray ban sunglasses,http://www.rayban-sunglasses.org.uk/ ray-ban sunglasses,http://www.rayban-sunglasses.us.org/ ray ban sunglasses outlet,http://www.raybansunglassesoutlet.net.co/ ray ban wayfarer,http://www.raybanwayfarer.in.net/ replica handbags,http://www.replicahandbags.com.co/ rolex watches,http://www.replica-watches.us.com/ retro jordans,http://www.retro-jordans.com/ rolex watches,http://www.rolex-watches.me.uk/ nike roshe,http://www.rosherun.org.uk/ roshe run,http://www.rosheruns.us/ salvatore ferragamo,http://www.salvatoreferragamo.in.net/ soccer shoes,http://www.soccer-shoes.org/ baseball bats,http://www.softball-bats.us/ supra shoes,http://www.suprashoes.in.net/ swarovski crystal,http://www.swarovskicrystal.com.co/ swarovski jewelry,http://www.swarovskijewelry.com.co/ swarovski,http://www.swarovski-uk.org.uk/ the north face,http://www.the-northface.com.co/ the north face jackets,http://www.the-northface.in.net/ north face,http://www.thenorth-face.org.uk/ north face outlet,http://www.thenorthface.us.org/ north face outlet,http://www.thenorthfacejackets.in.net/ thomas sabo,http://www.thomas-sabo-uk.co.uk/ tiffany and co,http://www.tiffanyandco.net.co/ tiffany jewelry,http://www.tiffanyjewelry.us.org/ timberland outlet,http://www.timberlandboots-outlet.in.net/ timberland boots,http://www.timberlandshoes.com.co/ tommy hilfiger outlet,http://www.tommyhilfiger.net.co/ tommy hilfiger kids,http://www.tommy-hilfigeroutlet.com/ toms shoes outlet,http://www.toms-shoes-outlet.net/ toms outlet,http://www.toms--outlet.in.net/ toms shoes,http://www.toms-shoes.com.co/ tory burch outlet,http://www.tory-burch-outlet.in.net/ tory burch outlet,http://www.tory-burchoutlet.us.com/ true religion,http://www.true-religion.com.co/ true religion jeans,http://www.truereligionjeans.net.co/ true religion outlet,http://www.truereligion-outlet.com.co/ ugg australia,http://www.ugg-australia.in.net/ ugg boots,http://www.uggboots.net.co/ ugg boots clearance,http://www.uggbootsclearance.com.co/ uggs on sale,http://www.uggsonsale.com.co/ uggs outlet,http://www.uggsoutlet.com.co/ coach outlet,http://www.uptocoachoutlet.com/ vans shoes,http://www.vansshoes.us/ wedding dresses,http://www.weddingdressesuk.org.uk/ yoga pants,http://www.yogapants.com.co/ ugg boot sale,http://www.ugg-boots.us.org/ polo ralph lauren outlet,http://www.poloralphlaurenoutlet.net.co/ burberry outlet online,http://www.burberryoutletonline.ar.com/ toms outlet,http://www.toms-outlet.net.co/ michaelkors.com,http://www.michaelkors.in.net/ christian louboutin,http://www.christianlouboutinoutlet.net.co/ tory burch sale,http://www.toryburchsale.com.co/ prada outlet,http://www.pradaoutlet.com.co/ longchamp handbags,http://www.longchamp-handbags.in.net/ longchamp outlet,http://www.longchampoutlet.com.co/ chanel bags,http://www.chanel-bags.com.co/ true religion outlet,http://www.truereligion-outlet.us.org/ abercrombie and fitch kids,http://www.abercrombie-and-fitch.us.com/ hollister clothing,http://www.hollisterclothing.in.net/ new balance shoes,http://www.newbalance-shoes.org/ converse shoes,http://www.converses-shoes.net/ lululemon outlet,http://www.lululemonoutlet.com.co/ nfl jerseys,http://www.nfl-jersey.in.net/ cheap jerseys,http://www.cheapjerseys.us.org/ rolex watches,http://www.rolex-watches.us.com/ rolex watches for sale,http://www.rolexwatchesforsale.us.com/ p90x workout,http://www.p90xworkout.in.net/ giuseppe zanotti,http://www.giuseppezanotti.com.co/ mac cosmetics,http://www.maccosmetics.net.co/ instyler ionic styler,http://www.instyler.in.net/ mizuno wave,http://www.mizunorunning.net/ louboutin,http://www.christian-louboutin-shoes.ca/ air max,http://www.nike-air-max.ca/ bcbg max,http://www.bcbg-max-azria.ca/ ugg,http://www.uggscanada.ca/

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>