wp-admin AJAX with Fetch API

mail@pastecode.io avatar
unknown
php
a year ago
530 B
12
Indexable
Never
<script>
    
  var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";

  const btn = document.querySelector('.action-btn--loadmore');
  btn.addEventListener('click', (e) => {
		e.preventDefault();
    fetch(ajaxurl, 
			{
				method: "POST",
				headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
				},
				body: 'action=load_posts_by_ajax&_wpnonce=<?php echo wp_create_nonce("load_more_posts"); ?>',
			}
    )
		.then(res => res.text())
		.then(res => console.log(res));
  });
</script>