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' );
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() {
                url: ajaxurl,
                data: {
                    action: 'portfolio_ajax'
                success: function(data) {

                error: function(MLHttpRequest, textStatus, errorThrown){


<a href="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?

  • wp_localize_script should be called after the script is enqueued in phantom_scripts, though if ajaxurl doesn't exist you should be seeing an error for that.
    – Milo
    Aug 6, 2015 at 14:52

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:

/* ... */
    url: ajaxStuff.ajaxurl, // NOTE use of 'ajaxStuff' object
/* ... */

First you need to do what Dougal said about getting the ajax-url right. I would also specify the dataType. dataType is the type of data that you're expecting back from the server, you can read more about it here.

And I would use wordpress's get_template_part to get the template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.