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 â¦
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
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):
ajax script:
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:
Then within the php function the ajax is calling, you can retrieve them like so:
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.