2

I am currently studying Wordpress AJAX but keep getting error message (so the success function is not being executed)

Currently I have changed the header.php (of twentythirteen theme) to include JavaScript that sends AJAX Request.

<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
<?php wp_head(); ?>
<script type="text/javascript">

    jQuery(document).ready(function($){

    //AJAX
    $.ajax({

        type: "GET",
        dataType: "json",
        url: "<?php echo admin_url('admin-ajax.php'); ?>;",
        data: {
            action: 'xn_get_event'
        },
        success: function(response){
            alert("Yes");
        },
        error: function(response){
            alert("omg!");
        }

    }); //END OF AJAX (SEND REQUEST)
}); //END OF READY FUNCTION
</script>

And then in the theme folder, I have included another PHP file called json-feed.php inside functions folder (so theme_name/functions/json-feed.php) and here I included the following code:

header('Content-Type:application/json');


//Needs to include wp-load.php file! 
if(file_exists('../../../../wp-load.php')):
    include '../../../../wp-load.php';
else: //Double checking in case the path is wrong.
    include '../../../../../wp-load.php';
endif;

//AJAX Handler
add_action('wp_ajax_nopriv_xn_get_event', 'xn_get_event');
add_action('wp_ajax_xn_get_event', 'xn_get_event');

function xn_get_event(){

    echo "Wow!";

}

And then when I go to the website it keeps alerting "Omg!" to me and I do not know why it is keep returning error response!

2 Answers 2

5

There are tons of questions about using Ajax, so your question could be easily marked as duplicated but I see so BIG mistakes that I can't say to you that the question is duplicated without explaining your mistakes.

  1. The Ajax in Wordpress is handled in admin-ajax.php file, wehre you correctly sent the ajax request (see the url parameter of the Ajax call). So, you don't need to include wp-load.php, Wordpress is already loaded.
  2. The file json-feed.php from your theme folder is never executed unless you include it in the functions.php file or any descendant file.
  3. You always need to exit when the ajax action is ended (unlees you use wp_send_json and related functions that already perform the exit).
  4. You have a typo in the URL parameter of the Ajax request (see ; at the end).
  5. The content type specified in the repsonse header doesn't match the real content type of the response output.

For a quick working example include this code in the functions.php file and fix the typo in the URL parameter:

add_action('wp_ajax_nopriv_xn_get_event', 'xn_get_event');
add_action('wp_ajax_xn_get_event', 'xn_get_event');

function xn_get_event(){

    echo 'Wow!';
    exit;

}

Also, It is recommended to not include inline javascript directly in the header.php or any other template file when the javascrpt has dependencies, like your code. You never knows how the dependencies are handled. For example, your javascript depends on jQuery but the jQuery file can be moved to footer and your jQuery code will stop working because it is printed before jQuery is loaded. Use the proper Wordpress functions to include javascript and manage dependencies. A much better code would be:

add_action('wp_ajax_nopriv_xn_get_event', 'xn_get_event');
add_action('wp_ajax_xn_get_event', 'xn_get_event');

function xn_get_event(){

    $data = array( 'message' => 'Wow!' );
    wp_send_json( $data );

}

add_action('wp_enqueue_scripts', 'cyb_enqueue_scripts');
function cyb_enqueue_scriptss() {

    //Register my script
    //Update with the correct path to javscript file
    wp_register_script('my-script', get_stylesheet_directory_uri(). '/js/my-script.js', array( 'jquery' ) );

    //Enqueue scripts and dependencies
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'my-script' );

    //Localize js variables to be used in my-script.js
    $scriptData = array(
                      'ajaxurl' => admin_url('admin-ajax.php')
                     );
    wp_localize_script( 'my-script', 'my_script_data', $scriptData );

}

The content of my-script.js file could be something like:

jQuery(document).ready(function($){

    //AJAX
    $.ajax({

        type: "GET",
        dataType: "json",
        url: my_script_data.ajaxurl,
        data: {
            action: "xn_get_event"
        }
    })
    .done( function( response ) {
            alert( response.message );
    })
    .fail( function( response ){
            alert( "omg!" );
    });
});

For more information read the documentation on WP Ajax API or any othe millions of questions and examples about using Ajax in Wordpress.

Note: code not tested.

-3

Try to use complete instead of succes.

Also, including wp-load isn't the best practice, what is the reason that you are including it?

5
  • I have no concrete idea I just followed a tutorial without really understanding the fundamental reason for doing that :P Aug 30, 2014 at 10:27
  • Yeah I understand, I did the same thing some days ago. The reason is (if I'm correct) is that if you use this in a plugin, the relative path to wp-load may be wrong, as you can install a plugin anywhere in a Wordpress installation. What I advise, practice your Ajax in a plugin that you make, and use proper hooking. If you use proper hooking you don't have to include wp-load, as it is already loaded by Wordpress then. Aug 30, 2014 at 10:31
  • hmm but I do not understand why it keeps calling the error function it seems that there is nothing wrong with the code that I wrote.. Aug 30, 2014 at 10:33
  • 1
    Very incomplete answer, it would be a comment on the question instead.
    – cybmeta
    Aug 30, 2014 at 10:42
  • 1
    Ok, will keep this in mind the next time. Aug 30, 2014 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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