tschaki
create wordpress plugin
Home » WordPress: Call PHP function with Javascript

WordPress: Call PHP function with Javascript

Wordpress makes it possible: With Wordpress it is possible to execute PHP functions via Javascript or jQuery. If used correctly, all parameters and variables are transmitted and translateable.

Connection between PHP and Javascript

To establish the connection between Javascript and PHP, basically three code blocks are needed. This is used to call PHP via Javascript

The first part defines that we include a new Javascript file and localize it immediately. This javascript file can later contain the jQuery script. Primarily, this allows to translate Javascript content correctly with PHP and at the same time functions can be queried via AJAX.

Paste this function into the main file of your active theme or plugin.

function hook_tschaki_ajax( ){
    wp_enqueue_script( 'script-checker', plugin_dir_url( __FILE__ ) . 'js/script-checker.js' );
    wp_localize_script( 'script-checker', 'account_script_checker', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'fail_message' => __('Connection to server failed. Check the mail credentials.', 'script-checker'),
            'success_message' => __('Connection successful. ', 'script-checker')
        )
    );
}
add_action( 'enqueue_scripts', 'hook_tschaki_ajax' );
add_action( 'admin_enqueue_scripts', 'hook_tschaki_ajax' );

Code Definition

RowDescription
1.Function ‘hook_tschaki_ajax()’ is created.
2.script-checker.js is mounted as (empty) file.
3.AJAX URL is declared with function for JS (account_script_checker). Handle “script-checker” must be present on line 2 and 3.
4.Contains the standard AJAX URL of WordPress admin-ajax.php.
5./6.Translatable strings or values for Javascript execution.
10.Mount the function into the WordPress frontend as Javascript. (Using Ajax in the frontend)
11.Mount the function into the WordPress backend as Javascript. (Using Ajax in the backend)

PHP function to be executed

Right below the new code, the function to be called by Javascript can now be declared in PHP. Two actions are connected to the function:

  • wp_ajax_nopriv_check_tschaki_ajax
  • wp_ajax_check_tschaki_ajax

nopriv means that this function may also be executed by not logged in WordPress users.

The second hook is only used if the user is logged in, so is_user_logged_in() == returns true . Would be useful for example for functions that visitors should not execute.

Paste this function into the main file of your active theme or plugin.

function check_tschaki_ajax( ) {
    // entry here your function for ajax request
  	echo 'failed_connection';
}
add_action( 'wp_ajax_nopriv_check_tschaki_ajax', 'check_tschaki_ajax' );
add_action( 'wp_ajax_check_tschaki_ajax', 'check_tschaki_ajax' );

Javascript integration

With the following code the previously declared PHP function is executed by Javascript. The function is called on line 5 (‘check_tschaki_ajax‘).

Paste the code in Javascript of the active theme or plugin.

jQuery.ajax({
        type: 'POST',
        url: account_script_checker.ajaxurl,
        data: {
            action: 'check_tschaki_ajax',
            fail_message: account_script_checker.fail_message,
            success_message: account_script_checker.success_message
        },
        beforeSend: function ( ) {
            jQuery( 'body' ).html( account_script_checker.loading_message );
        },
        success: function ( data, textStatus, XMLHttpRequest ) {
            if( data === 'failed_connection0' ) {
                jQuery( '.checkmailstatus td' ).html( '<div class="error notice"><p>' + account_script_checker.fail_message + '</p></div>' );
            } else {
                jQuery( '.checkmailstatus td' ).html( '<div class="success notice notice-success"><p>' + account_script_checker.success_message + data + '</p></div>' );
            }
        },
        error: function ( XMLHttpRequest, textStatus, errorThrown ) {
            alert( errorThrown );
        }
    });

Trent Bojett

My name is Trent Bojett, I am 28 years old and I live in Switzerland. Because of my enthusiasm for writing and the logical world (= software development) I started this blog in early 2020.

1 comment

  • Hi Trent, Thanks for your tutorial! 🙂
    I just tried to follow the steps but I have a JS error when the function is played : “account_script_checker is not defined”.
    And it’s true, this var is not defined. Could you explain me what value I have to define?
    Thanks!
    Arthur