I have a link on my post edit page (admin side) that calls up AJAX and jQuery to run a function inside my functions.php page. The link is wired up and calling the jQuery but I can’t seem to debug whats going on inside my function thats being called from jQuery. I want the clicked link to delete custom metadata for the post (it is a custom post type) and then delete a file.

Here’s the code with the delete function at the end:

//Add AJAX functionality to post.php to delete files
add_action('admin_enqueue_scripts', 'my_admin_enqueue_scripts');
add_action('wp_ajax_delete_meta', 'delete_pdf_and_metadata');

//Add my custom JS to the header of admin
function my_admin_enqueue_scripts($hook) {
    global $current_screen;

    if ( 'post.php' != $hook )
        return;
    wp_register_script('my-scripts', get_template_directory_uri() . '/js/custom/my-scripts.js' );
    wp_enqueue_script('my-scripts');
    wp_localize_script('my-scripts', 'wp_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}

function delete_pdf_and_metadata() {

    global $post;

    //delete metadata
    $the_id = intval($_POST['the_id'] );
    $the_pdf = get_post_meta($post->ID, $the_id);

    delete_post_meta($post->ID, $the_id, $the_pdf['name']);

    //TODO Delete PDF 
}

Here’s the jQuery call:

jQuery(document).ready(function($) {
    $('.delete_pdf').each(function(i,e) { //grab the class delete-pdf
        var id = $(this).attr('id').replace(/delete-/, '');
        var li = $(this).closest('li');

        $(this).click(function(){

            $.post(ajaxurl, { action: 'delete_meta', the_id: id }, function(data){

                return id;
                });
        });

    });

});

Using FireBug all I see is for a response is 0. What is the best way to debug what is happening inside my function delete_pdf_and_metadata() being called via jQuery?

Thanks!

4 Answers
4

You aren’t echoing anything so you aren’t going to get much of an AJAX response. All you are doing with AJAX, really, is loading a webpage with Javascript. If the page doesn’t print anything, you don’t see anything. You don’t need to return anything from AJAX but if you don’t you will have a hard time working out whether your action was successful.

If you need to get information back, even for debugging, just echo it, or var_dump it. You will be able to see your echoed or var_dumped content with FireBug. Be aware that if your AJAX content is supposed to be something like JSON this debugging hack will break it.

Also, it kinda looks like you expect an ID to come back from your AJAX call. You will need to echo that in the delete_pdf_and_metadata function, or build a JSON object and echo that.

Leave a Reply

Your email address will not be published. Required fields are marked *