Debug whats going on inside a function called from AJAX

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:

Read More
//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!

Related posts

Leave a Reply

4 comments

  1. 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.

  2. I use the following to catch things that FireBug doesn’t:

    function print_log( $msg, $title = '' )
    {
        $error_dir = '/Applications/MAMP/logs/my.log';
        // or
        // $error_dir = '/home/user/public_html/wp-content/mu-plugins/my.log';
        $date = date('d.m.Y h:i:s'); // not used in this function
        $msg = print_r($msg,true);
        $log = $title."  |  ".$msg."n";
        error_log( $log, 3, $error_dir );
    }
    

    Hope this helps…

  3. The one thing is to simply add an echo/var_dump/var_export/print_r() around what you want to debug and then watch your Chrome DevTools, FireBug, etc. Console for the output.

    If you want to print it directly on the screen then wrap around an exit() and you’ll get only this part back.

  4. If you be experienced enough, write a database-logger. This could be a simple class with a databse connection and some read/write/update methods

    class DB_Logger
    {
    
      // not needed if you use the WordPress Database    
      private $db_name = 'database';
      private $db_table = 'tablename';
      private $db_user = 'username';
      private $db_password = 'password';
      private $db_host = 'localhost';
    
      // instance of WordPress' $wpdb
      private static $db = null;
    
      private static $connection = null;
    
      public function __construct(){
        if( null === self::$connection )
          $this->connect();
      }
    
      public function connect(){
        global $wpdb;
    
        if( null === $this->db )
          $this->db = $wpdb;
    
        [or connect to another, none WordPress database]
      }
    
      public function write( $msg = '' ){
        [write message to database]
      }
    
      public function read( $type = 'all' ){
        [read message)s) from database]
      }
    
      public function erase( $type = 'all' ){
        [delete message(s) from database]
      }
    }
    

    Include the class in your php-file and log messages to the database

    include_once 'path/to/your/class/class-db_logger.php';
    
    $logger = new DB_logger();
    
    [some code]
    
    $logger->write(
      '$var at line ' . __LINE__ . ' in file ' . __FILE__ . ': ' . var_export( $var, TRUE )
    );
    

    With a bit of PHP and a bit of Ajax you can now periodically request your debbugging infos from the database and display them e.g in the admin bar, header or footer.

    FireBug is a great tool, but the debugging infos are lost with the next page reload. Sometimes it could be helpfull to see how things change by changing the code.