• Hi,

    currently i’am using this code to handle my form submit via ajax request (included in the functions.php of my theme):

    add_action('wp_ajax_form_booking', 'handle_form_booking');
    add_action('wp_ajax_nopriv_form_booking', 'handle_form_booking');
    
    function handle_form_booking()
    {
    	die("so many stuff to do...");
    }

    But this code will be loaded every time, on every page. Can i tweak this for performance reasons, best only loading in one specified template file? Like “pseudo”:

    <?php
    
    /**
     * Template Name: Home
     * Template Post Type: page
     *
     * @package ...
     * @version ...
     */
    
    add_action('wp_ajax_form_booking', 'handle_form_booking');
    add_action('wp_ajax_nopriv_form_booking', 'handle_form_booking');
    
    function handle_form_booking()
    {
    	die("so many stuff to do...");
    }

    … This code will return 0, every time. Not return the die();

    Thanks.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You’re not completely right with what you’re saying. Setting up the AJAX callbacks doesn’t mean that they load on every page. It means that they will be checked on AJAX calls – and that doesn’t happen on a standard page load.

    Just leave them in as they are in the functions.php file as the only “performance hit” will be the couple of milliseconds (max) of adding the actions to the global lsit of actions. There’s no other overheard.

    Thread Starter danielwerner23

    (@danielwerner23)

    Why i cant split these things?

    in the functions.php:

    add_action('wp_ajax_form_booking', 'handle_form_booking');
    add_action('wp_ajax_nopriv_form_booking', 'handle_form_booking');

    in my template file:

    function handle_form_booking()
    {
    	die("so many stuff to do...");
    }

    the reason is, my function is massive and thats a lot to load, every page and thats not that performant.

    Moderator bcworkz

    (@bcworkz)

    Your code may be loaded as part of WP initialization, but it does not execute until the Ajax call. Have you assessed the size of the overall WP code base? It’s hard to imagine your large function amounts to anything relative to the overall code that gets loaded.

    How would you split things up? Isn’t it all needed for the Ajax call? If it’s not needed, why have it in place at all? There may be opportunities to streamline the Ajax callback so it executes faster, but whether it gets loaded or not is trivial, don’t worry about it.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Ajax Form Handle Action outside functions.php’ is closed to new replies.