How to load and display a view with Ajax in Drupal 7?
This is the first time I've ever tried to load a view using Ajax in Drupal7 and I would be appreciated if you help me from scratch. I've spent hours to learn how to do this but I still failed!
I created a view called image_gallery
, it has three blocks called hd
,tablet
and phone
and it displays set of images.I created a tab and I want to display and load these blocks (generally views) with Ajax. this my HTML:
<div>
<div id="image_gallery_tab">
<ul>
<li id="igt1">HD</li>
<li id="igt2">Tablet</li>
<li id="igt3">Cellphone</li>
</ul>
</div>
<div id="image_gallery_content">
<div class="igc" id="igc1">
<?php print views_embed_view("image_gallery","hd") ?>
</div>
<div class="igc" id="igc2">
</div>
<div class="igc" id="igc3">
</div>
</div>
</div>
I set the Use Ajax
to "yes" in the views UI. this is my jQuery code:
$("#image_gallery_tab ul li").click(function(){
var id = $(this).attr("id").slice(-1);
$(".igc").css("display","none");
if(id==2)
{
$.ajax({
url: Drupal.settings.basePath + 'views/ajax',
type: 'POST',
dataType: 'json',
data: 'view_name=image_gallery&view_display_id=tablet', // Pass a key/value pair.
success: function(response) {
$("#igc2").innerHTML=response.display;
},
error: function(data) {
alert('An error occured!');
}
});
}
});
but it displays nothing. what is wrong here and what shall I do? thanks
Answers 1
For anyone who ends up here looking for an answer, this is how you do it. First you need to enable "Use AJAX" under Other settings in the view and take note of the "Machine Name" as that is your display ID:
Then, this is how you pull it with JS using jQuery ajax: