I want to build an image slider that shows images with related heading and detail for each item. The data needs to be pulled from JSON. For example I stored the images like this.
items[
{
"image" : "images/item-1.png",
"heading" : "heading-1",
"text" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
},
{
"image" : "images/item-2.png",
"heading" : "heading-2",
"text" : "Morbi tincidunt commodo scelerisque."
},
{
"image" : "images/item-3.png",
"heading" : "heading-3",
"text" : "Duis porttitor diam vitae leo elementum accumsan."
}
]
How do I do this with jquery / ajax? I am beginner, can someone help? thanks for your time.
Well first of all it depends on what slider you use. An abstract approach would be something like this.
$(document).ready(function(){
getSlides();
})
function getSlides(){
var request = $.ajax({
type: "POST",
url: 'script.php',
data: {
action: "get_slilder_images"
},
dataType: "json"
});
request.done(function( response ) {
createSlides(response);
// fires on successfull reply
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
// fires on error
});
request.done(function() {
// fires everytime transaction completes with or withoute error
})
}
function createSlides(slides){
var container = $('#sliderContainer');
var html = '';
for(var i = 0; i < slides.length; i++){
html += '<li class="slide"><span class="slide-header">' + slides[i].heading + '</span><img src="' + slides[i].image + '"><span class="slide-text">' + slides[i].text + '</span></li>';
}
html = '<ul class="slide-list">' + html + '</ul>';
container.html(html);
container.someSliderPlugin(); // here it depends on what slider you use, most of them take a list as input.
}