Last active
June 19, 2018 19:40
-
-
Save marcelo-ribeiro/9c0be606adc7dd3048683f02c68da364 to your computer and use it in GitHub Desktop.
Javascript Ajax Cross-browser - Method POST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
}); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My Infinite Scroll - Pure Javascript
https://codepen.io/marcelo-ribeiro/pen/EwKKrZ