Support » Developing with WordPress » Why does an add_action hook lead to 500 error?

  • Resolved iamjustalex

    (@iamjustalex)


    Hello,

    I have code:

    <?php
    
    add_action( 'contactme', 'contact', 10 );
    
    function contact() {
      echo 'Success';
      wp_die();
    }
    
    do_action('contactme');
    
    ?>

    For some reason it evokes a 500 error and I don’t have a clue how to fix it.

    Here are the logs:

    Error getting response code, most likely a stopped request
    
    Array
    (
        [url] => https://website.com/wp-cron.php?doing_wp_cron=1654995883.2758231163024902343750
        [args] => Array
            (
                [method] => POST
                [timeout] => 0.01
                [redirection] => 5
                [httpversion] => 1.0
                [user-agent] => WordPress/6.0; https://website.com
                [reject_unsafe_urls] => 
                [blocking] => 
                [headers] => Array
                    (
                    )
    
                [cookies] => Array
                    (
                    )
    
                [body] => 
                [compress] => 
                [decompress] => 1
                [sslverify] => 
                [sslcertificates] => /home/myname/website.com/wp-includes/certificates/ca-bundle.crt
                [stream] => 
                [filename] => 
                [limit_response_size] => 
                [time_start] => 1654995883.2794
                [_redirection] => 5
                [time_stop] => 1654995884.2844
                [duration] => 1004.9660205841
            )
    
        [r] => Array
            (
                [headers] => Requests_Utility_CaseInsensitiveDictionary Object
                    (
                        [data:protected] => Array
                            (
                            )
    
                    )
    
                [body] => [omitted]
                [response] => Array
                    (
                        [code] => 
                        [message] => 
                    )
    
                [cookies] => Array
                    (
                    )
    
                [filename] => 
            )
    
        [class] => Requests
        [stack_trace] => Array
            (
                [0] => Debug_Bar_WP_Http->after_http_request
                [1] => WP_Hook->apply_filters
                [2] => WP_Hook->do_action
                [3] => do_action('http_api_debug')
                [4] => WP_Http->request
                [5] => WP_Http->post
                [6] => wp_remote_post
                [7] => spawn_cron
                [8] => _wp_cron
                [9] => WP_Hook->apply_filters
                [10] => WP_Hook->do_action
                [11] => do_action('wp_loaded')
                [12] => require_once('wp-settings.php')
                [13] => require_once('wp-config.php')
                [14] => require_once('wp-load.php')
                [15] => require_once('wp-admin/admin.php')
            )
    
    )

    Could you please help me to understand how to fix it?
    The code works perfectly good if I remove the hook.
    Thank you in advance.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The wp_die() function always returns an HTTP status of 500 if nothing else is specified. See manual: https://developer.wordpress.org/reference/functions/wp_die/

    The code here would return an HTTP status of 200:

    add_action( 'contactme', 'contact', 10 );
    
    function contact() {
    	echo 'Success';
    	wp_die('', '', ['response' => 200]);
    }
    
    do_action('contactme');
    Thread Starter iamjustalex

    (@iamjustalex)

    @threadi Thank you very much for the explanation. But unfortunately I get POST 500 error even if I delete the line with wp_die().
    And I don’t get any echo.

    Thread Starter iamjustalex

    (@iamjustalex)

    I didn’t say, I thought it is not important, but I call this PHP with AJAX.
    The JS Script looks like this:

    (function($){
        $(document).ready(function() {
            $( '.formbtn' ).click( function(e) {
                e.preventDefault();
                $('.output_message').text('Loading...');
                $.ajax({
                  url: ajax_object.ajaxurl,
                  type: 'POST',
                  data: {
                  },
                  success: function( response ) {
                      console.log('The server responded: ',response);
                  },
                });
           });
       });
    })(jQuery);

    ajax_object.ajaxurl I get from a hook in functions.php:

    function load_scripts()
    {
        wp_enqueue_script( 'contact_form', get_template_directory_uri() . '/contact_form/contact_form.js', array('jquery') );
          wp_localize_script( 'contact_form', 'ajax_object',
            array(
                'ajaxurl' => get_template_directory_uri() . '/email.php'
            )
        );
    
    }
    add_action('wp_enqueue_scripts', 'load_scripts');

    So, everything works properly if I remove the hook in PHP file. But if I keep the hook I get POST 500 Error in the console. And unfortunately I don’t have a clue how to fix it.I would be very thankful if somebody give me an idea how to solve this problem.

    I called this once just like you – via POST using wp-cron.php. I don’t get any error 500 there but also no output. There is not, because the call via wp-cron.php works a bit different. If you want to have an output there, you have to realize it via the init hook. Look here: https://wordpress.stackexchange.com/questions/13625/how-to-debug-wordpress-cron-wp-schedule-event

    Moderator bcworkz

    (@bcworkz)

    Your problem likely lies in the email.php file your Ajax submits to. FYI, you’re not following the recommended way to implement Ajax in WP. The way you’re doing it is probably not 100% portable to other WP installations. This is why the recommended Ajax process is to submit through /wp-admin/admin-ajax.php. You then hook an action that is in part named after the “action” query var value your jQuery would send. More on this in the Plugin Handbook.

    This is not to say you cannot do it your way. Done correctly, it will work on your site. Maybe not mine, but it could suit your specific need.

    Dion

    (@diondesigns)

    Have you checked your PHP error log to determine the actual error being generated?

    Having said this, if the code in your first post is the entirety of your email.php file, then it will generate a PHP fatal error because the add_action() and do_action() functions are part of the WordPress core, and your file isn’t loading WordPress.

    WordPress has its own AJAX handler system. Documentation:

    https://developer.wordpress.org/plugins/javascript/ajax/

    EDIT: posted a bit too late! 🙂

    Thread Starter iamjustalex

    (@iamjustalex)

    @bcworkz – Thank you so much for your advice. It really has helped. Now my script finally works. The problem indeed was that I put the php code to a separate file instead of /wp-admin/admin-ajax.php, I thought that it was unnecessary, but it turned out that AJAX has some strict rules which a developer has to follow.
    My big thank to you.

    • This reply was modified 1 week, 5 days ago by iamjustalex.
    Thread Starter iamjustalex

    (@iamjustalex)

    @threadi, @diondesigns Thank you very much for you responses! The problem has been solved, as I mentioned, I used AJAX and I had to put the PHP code not into a separate file but into wp-admin/admin-ajax.php.
    The actual code is a little bit different, I made the initial code trying to debug a problem, but the problem was just a wrong place for the php code.
    The actual code is:

    add_action( 'wp_ajax_contactme', 'my_ajax_handler' );
    add_action( 'wp_ajax_nopriv_contactme', 'my_ajax_handler' );
    
    function my_ajax_handler() {
          check_ajax_referer( 'title_example' );
          echo 'Success';
          wp_die(); // All ajax handlers die when finished
    }

    Thank you everybody! Have a great week!

    • This reply was modified 1 week, 5 days ago by iamjustalex.
    • This reply was modified 1 week, 5 days ago by iamjustalex.
Viewing 8 replies - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.