Hello!
I’m moving a theme from Sage 9 to Sage 10. All is fun and well until I got to the Ajax part. This is to my knowledge the final problem before completion, and I’m losing my hair as we speak!
The error from the console log:
article.9c7e8e.js:1 Uncaught ReferenceError: ajaxArticle is not defined
at article.9c7e8e.js:1:461
at HTMLAnchorElement.<anonymous> (article.9c7e8e.js:1:821)
at HTMLAnchorElement.dispatch (jquery.js?ver=3.7.1:5145:27)
at elemData.handle (jquery.js?ver=3.7.1:4949:28)
ajax.php:
namespace App;
class Ajax
{
public function __construct()
{
add_action('wp_ajax_get_articles', [$this, 'getArticles']);
add_action('wp_ajax_nopriv_get_articles', [$this, 'getArticles']);
}
public function getArticles()
{
// Code working on Sage 9 here!
}
}
setup.php:
add_action('wp_enqueue_scripts', function () {
bundle('main')->enqueue();
if (is_post_type_archive('article')) {
bundle('article')->enqueue();
wp_localize_script('sage/article.js', 'ajaxArticle', ['ajaxURL' => admin_url('admin-ajax.php')]);
}
article.js:
let currentPage = 1
let maxTotalPages
const adContainer = []
jQuery(document).ready(function ($) {
maxTotalPages = $('.article-container').data('max_num_pages')
adContainer.push({
id: $('.ad-container').data('id'),
maxViews: Number($('.ad-container').data('max_num_views')),
currentViews: 1,
})
$('.load-more').on('click', (e) => {
e.preventDefault()
loadArticles()
})
function loadArticles() {
const params = {
page: currentPage + 1,
ads: adContainer,
}
$.ajax({
url: ajaxArticle.ajaxURL, // eslint-disable-line no-undef
type: 'POST',
data: {
action: 'get_articles',
params: JSON.stringify(params),
},
success: (response) => {
currentPage++
// Logic for ads
if (response.currentAd) {
let find = adContainer.find(x => x.id === response.currentAd.ID)
if (find) {
find.currentViews++
} else {
adContainer.push({
id: response.currentAd.ID,
maxViews: Number(response.currentAd.max_views),
currentViews: 1,
})
}
}
$('.article-container').append(response.html)
if (currentPage === maxTotalPages) {
$('.load-more').remove()
}
},
error: (error) => {
console.log(error)
},
})
}
})