Wordpress call php function from javascript

Here's an example:

Use this sample JavaScript code:

jQuery(document).on('click', '.some-element', function(e){
    var ipc = jQuery(this).data('collection-id');
    jQuery('.some-other-element').show();

    jQuery.ajax({
        method: 'post',
        url: ipAjaxVar.ajaxurl,
        data: {
            collection_id: ipc,
            action: 'my_function',
        }
    }).done(function(msg) {
        // Do something when done
    });

    e.preventDefault();
});

PHP (include the function in your plugin, do not use a separate file):

// Include the JavaScript above in your plugin
wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);

wp_localize_script('main', 'ipAjaxVar', array(
    'ajaxurl' => admin_url('admin-ajax.php')
));

add_action('wp_ajax_my_function', 'my_function');

UPDATE:

Add the PHP code to your main plugin file. Create a JavaScript file - js/jquery.main.js - and add the code above. That should do the trick.

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

Row Description
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.

Can JavaScript call a PHP function?

The reason you can't simply call a PHP function from JavaScript has to do with the order in which these languages are run. PHP is a server-side language, and JavaScript is primarily a client-side language.

How do I call a JavaScript function from WordPress?

How to Add Custom JavaScript to WordPress (3 Methods).
Use the Head & Footer Code plugin (the simplest option for non-technical users).
Add code to functions. php file..
Add code to header (using the wp_enqueue_script function or the wp_head hook).

How do you call a function in PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );

How do I call a PHP function from another file?

To call a function from another file in PHP, you need to import the file where the function is defined before calling it. You can import a PHP file by using the require statement. To call the greetings() function from another file, you need to import the library.