Skip to content

Instantly share code, notes, and snippets.

@marcelo-ribeiro
Last active June 19, 2018 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelo-ribeiro/9c0be606adc7dd3048683f02c68da364 to your computer and use it in GitHub Desktop.
Save marcelo-ribeiro/9c0be606adc7dd3048683f02c68da364 to your computer and use it in GitHub Desktop.
Javascript Ajax Cross-browser - Method POST
var postsList = document.querySelector('.posts_list');
var paged = 1;
var countPosts = postsList.dataset.countPosts;
var postsPerPage = parseInt(postsList.dataset.postsPerPage);
window.addEventListener( 'onInfinite', getPosts );
function hasMoreItens() {
return postsList.children.length < countPosts;
}
function getPosts() {
paged++;
var data = {
paged: paged
};
myAjax({
url: ApitUrl + 'portfolio.php',
data: data,
success: function( response ) {
postsList.insertAdjacentHTML( 'beforeend', response );
if ( hasMoreItens() )
InfiniteScroll.complete();
else
InfiniteScroll.stop();
}
});
}
// MY_AJAX_FUNCTION
// ----------------
function myAjax(params) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); // code for IE7, firefox chrome and above
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // code for Internet Explorer
}
xhr.withCredentials = params.withCredentials || false;
xhr.open('POST', params.url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = Object.keys(params.data).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params.data[key]);
}).join('&');
xhr.send(data);
xhr.addEventListener('readystatechange', function () {
if (this.readyState === 4 && this.status === 200) {
params.debug && console.log(this);
params.success(this.responseText);
}
});
}
@marcelo-ribeiro
Copy link
Author

marcelo-ribeiro commented Mar 5, 2018

My Infinite Scroll - Pure Javascript
https://codepen.io/marcelo-ribeiro/pen/EwKKrZ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment