Click loads template via ajax

I’m trying to load a template via ajax if the user clicks on a button. This is the code I’m using:

On functions.php:

function phantom_scripts() {
  global $child_dir;

  /* Ajax Requests */
  wp_enqueue_script( 'ajax-stuff', get_stylesheet_directory_uri() . '/js/ajax.js', array( 'jquery' ), true );
 }
 add_action( 'wp_enqueue_scripts', 'phantom_scripts' );


function portfolio_ajax() {
  include( 'templates/cards.php' );
  die();
}
add_action('wp_ajax_nopriv_portfolio_ajax', 'portfolio_ajax');
add_action('wp_ajax_portfolio_ajax', 'portfolio_ajax');

wp_localize_script( 'ajax-stuff', 'ajaxStuff', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

On ajax.js:

(function($) {
    $('#load-cards').click(function() {
        alert();
            $.ajax({
                url: ajaxurl,
                data: {
                    action: 'portfolio_ajax'
                },
                success: function(data) {
                    $('#cards-container').append(data);
                },

                error: function(MLHttpRequest, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        });
})(jQuery);

HTML:

<a href="https://wordpress.stackexchange.com/questions/196868/javascript:void(0)" id="load-cards">Load cards</a>

Right now, the console is not showing to me any error but is not loading the content I have in templates/cards.php file. Any idea what I’m missing?

2 Answers
2

So, you’re using wp_localize_script to inject the ajax url. But you didn’t use the localized var handle to access that value. Try this:

/* ... */
$.ajax({
    url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object
/* ... */

Leave a Comment