I am using the following script to load some Wordpress posts. Unfortunately this replaces my content and I would like to append to the existing content.
What is your suggestion on appending using AJAX call.
$('#load-posts a').click(function() {
if(pageNum <= max) {
$('#content').load(nextLink + ' article',
function() {
// Update page number and nextLink.
// Update the button message.
}
}
);
}
});
Thanks
$(init); function init() { $. ajax({ dataType: "json", url: "http://www.omdbapi.com/?i=tt0111161", success: function (data) { console. log(data); $("#movie-data"). append(data); } });
The jQuery append() method is used to insert specified content as the last child (at the end of) the selected elements in the jQuery collection. The append () and appendTo () methods are used to perform the same task. The only difference between them is in the syntax. Syntax: $(selector).
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
append() & . prepend() .append() puts data inside an element at the last index; while. . prepend() puts the prepending element at the first index.
load()
replaces the content, but it's basically just a shortcut for $.get, so use that instead.
$('#load-posts a').click(function() {
if(pageNum <= max) {
$.get(nextLink + ' article', function(data) {
$('#content').append(data);
});
}
});
If filtering specific elements with load(), you will have to do that yourself.
load replaces the content of the parent. One way of doing it is loading content to a new div and than appending it to the element.
$("<div>").load(nextLink + ' article', function() {
$("#content").append($(this).html());
});
I would use getJson method to get a JSON response where i have 3 parts. one for the Content , another for the NextLink and Third for the PateNumber. Then i will read the Json Result and use it in the relevant place.
You can return a JSON like this
{
"Content": "<p>Some New Content</p>",
"NextLink": "page.php?no=34",
"PageNumber": "34"
}
and in your getJSON
, you can read the items and use it
$('#load-posts a').click(function() {
if(pageNum <= max) {
$.getJSON(nextLink,function(jSonResult){
$('#content').append(jSonResult.Content);
$("#nextLink").html(jSonResult.NextLink);
$("#pageNumber").html(jSonResult.PageNumber);
});
}
});
if(pageNum <= max) {
$('body').append($('<div id="hiddenContainer" style="display:none"></div>')); // a hidden container to store response
$('#hiddenContainer').load(nextLink + ' article',
function() {
$('#content').append($('#hiddenContainer').html());
}
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With