I have the following code in functions.php
<script type="text/javascript">
var post_id = "1055"; // hardcoded post id for testing purposes
var type = "some_type";
var data = {action: "get_variations", parent_id: post_id, item_type: type};
jQuery.post("/wp-admin/admin-ajax.php", data, function(response){
alert(response);
});
</script>
<?php
function get_variations($parent_id, $item_type){
// etc..
}
add_action('wp_ajax_get_variations', 'get_variations', 10, 2);
?>
When ajax tries to call get_variations I always get:
Warning: Missing argument 2 for get_variations()
What am I doing wrong?
Ajax-calls use the
$_POST
-variable to submit their arguments to the function. As$_POST['action']
is always used by WordPress Ajax calls (contains the name of the action, obviously 😉 ), PHP only complains over missing argument no. 2.You can either use the solution provided by Bainternet. If you want to use your function in ajax as well as “pure” PHP context, you can do it this way:
This way, PHP will always assume the two arguments given, and you can also use this function without
$_POST
.Your ajax callback has no arguments,
this should work: