Function call via ajax – can’t figure it out?

In my header.php file I’ve got …

<script type="text/javascript">
    var ajaxurl = "<?php echo admin_url( 'admin-ajax.php', 'relative' );?>";
</script>

In my functions.php file I’ve got …

Read More
add_action('wp_ajax_get_event_list', 'get_event_list');
add_action('wp_ajax_nopriv_get_event_list', 'get_event_list');

function get_event_list( $latest = true, $order = 'ASC', $return = false, $year = NULL, $cat = NULL ) {

    // Stuff of the function

}

In my script.js file I’ve got …

$('#year-filter .inactive').click(function(e) {
    e.preventDefault();
    console.log(ajaxurl); // http://mydomain.com/wp-admin/admin-ajax.php 

    $.ajax({
        type: 'GET',
        url: ajaxurl,
        data: { 
            action: 'get_event_list',
            year: '2012', //param year
            cat: 'vortraege' //param category
        },
        dataType: 'html',
        timeout: 300,
        success: function(data){
            console.log('Ajax success');
        },
        error: function(xhr, type){
            console.log('Ajax error');
            console.log(xhr + " " + type)
        }
    });
});

I currently get the following error in my console

http://mydomain.com/wp-admin/admin-ajax.php

Ajax error

[object XMLHttpRequest] timeout

Related posts

1 comment

  1. You need the url to the admin ajax script. You can go ahead and cheat and just use “/wp-admin/admin-ajax.php” as the url, it will try to locate it at the base of your domain.

    However a much better method is to print the ajax url out as javascript variable in the header and then reference it in your script like so:

    header.php (above the file the needs the ajaxurl):

    <script>
        var ajaxurl = "<?php echo admin_url( 'admin-ajax.php', 'relative' );?>";
    </script>
    

    ajax script:

    $.ajax({
        type: 'GET',
        url: ajaxurl,
        ....
    

    That will have your ajax calls pointing at the right place.

    To send additional data with the ajax for your php function to you should include it in the data object of the jQuery ajax method. This is the same place you’ve already declared the name of your php function.

    For example:

    data:{
        action: 'your_ajax_function',
        var1: 'some string',
        var2: 23,
        var3: 'another string'
    }
    

    Then within the php function the ajax is calling, you can retrieve them like so:

    var1 = $_GET ['var1']; // some string
    var2 = $_GET ['var2']; // 23
    

    If you were using post as the ajax type instead of get, then you’d access them using the $_POST variable instead of the $_GET one.

Comments are closed.