I have a slider on homepage, i am trying to load next five posts in it on click of a button using Ajax. When i use Jquery .post to load the html of next five posts, the slider disappears.The cause being that a script called 'slider.js' does not work on the newly added html. I tried using .live() but it didn't work, i can see the response from Ajax call in my console so i know tha call is working. I tried including the js file in Ajax response but it doesn't fire even then. The js file is a long file with a lot of functions, i cannot enclose it in one function as suggested by some people on the forum. How would i reload the slider.js to make it work? Here is the ajax .post() code.
$(function() {
$('.nextfive').live('click', function() {
var data = {action: 'next_five',next: 5};
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
function(response) {
$('#navi').slideDown("slow");
$("#slidercontainer").html(response);
},"html");
});
});
Edit: check the page at http://axactsoft.com/samplewp/ and click the button on top 'click five'. The code of files is pasted here http://pastebin.com/4iS6Ey10
Try with this:
$('.nextfive').on({
click: function () {
var data = {action: 'next_five',next: 5};
$.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
function (response) {
$('#navi').slideDown("slow");
$("#slidercontainer").html(response);
}
}
}, 'body');
You must use jquery 1.7 or above to use the .on() function. It's hard to know what you're doing without seeing the HTML structure of all the div IDs you're using.
I would also recommend splitting your code: you have an event handler that holds a function for ajax that itself nests a function to handle the ajax callback. I'd have the event handler handle the event and pass the parameter to a different function that handles just the ajax, and have that function call a function that handles just the processing of the ajax response. You should 3 functions in the same scope instead of having 3 functions nested into each other.
What slider.js are you using? You can probably add an event listener to reinitialize the slider after getting the data from your php script. Something like this, though it will vary based on how the slider works.
$('.nextfive').click(function () {
$.get("<?php echo admin_url('admin-ajax.php'); ?>",
{action :'next_five', next : 5},
function (resp) {
$('#navi').slideDown("slow");
$("#slidercontainer").html(response)
$("#slidercontainer").slider(); /* This will change depending on
* the library you are using */
});
})
Also, a couple of things about your coding style:
If you give more details about the slider you're using, I can help with more specific code.
Good luck! 4. Other small simplifications, you don't need to define the var data if you're using it only once, again see my example.