Last active
October 17, 2024 20:34
-
-
Save AbmSourav/79ccb8cc1ad6641a6aa2dcda24a794de to your computer and use it in GitHub Desktop.
WordPress ajax call with Fetch API
This file contains 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
// php file | |
function enqueue_scripts() { | |
wp_enqueue_script( 'public-js', plugin_dir_url( __FILE__ ) . 'js/script.js', array(), '1.0', true ); | |
wp_localize_script( 'public-js', 'localizeObj', | |
[ | |
'ajax_url' => admin_url( 'admin-ajax.php' ), | |
'nonce' => wp_create_nonce( 'prefix_public_nonce' ), | |
] | |
); | |
} | |
function load_more_posts() { | |
$security = check_ajax_referer( 'prefix_public_nonce', 'security' ); | |
if ( false == $security ) { | |
return; | |
} | |
// post query, loop... | |
} | |
add_action('wp_ajax_load_more_posts', 'load_more_posts' ); | |
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts' ); | |
// script.js file | |
const target_div = document.querySelector('.posts'); | |
const bodyParams = { | |
action: 'action=load_more_posts', | |
nonce: '&security=' + localizeObj.nonce, | |
} | |
fetch(localizeObj.ajax_url, { | |
method:"post", | |
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | |
body: bodyParams.action + bodyParams.nonce | |
}) | |
.then(function(res) { | |
return res.text(); | |
}) | |
.then(function(data) { | |
// console.log(data); | |
const parser = new DOMParser(); | |
const items = parser.parseFromString(data, 'text/html'); | |
const postItems = items.querySelectorAll('.items'); | |
postItems.forEach(function(postItem) { | |
target_div.append(postItem); | |
}); | |
}) | |
.catch(function (error) { | |
console.log(error.message); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment