Introduction

Running PHP function via JS using Ajax is a common practice in web development for several reasons:

1. Asynchronous Communication:

  • Ajax allows for asynchronous communication between the client (browser) and the server.
  • PHP functions, being server-side, can be executed without reloading the entire page. This provides a smoother and more responsive user experience.

2. Dynamic Content Update:

  • PHP functions often perform server-side operations, such as querying a database or processing data.
  • By calling PHP functions via Ajax, you can update specific parts of a web page dynamically based on the server’s response, without requiring a full page reload.

3. User Interaction:

  • Ajax enables you to handle user interactions, like button clicks or form submissions, without navigating away from the current page.
  • You can use JavaScript to trigger PHP functions in response to user actions, providing a more interactive and dynamic user interface.

4. Reduced Server Load:

  • By executing specific PHP functions via Ajax, you can reduce the load on the server by fetching only the data needed for a particular operation.
  • This can be more efficient than reloading the entire page and processing unnecessary server-side logic.

5. Real-time Updates:

  • Ajax facilitates real-time updates by allowing the client to communicate with the server in the background.
  • PHP functions can be used to generate real-time data, and the results can be updated on the client-side without requiring a page refresh.

6. Progressive Enhancement:

  • Separating the PHP functionality from the presentation layer (HTML/JavaScript) promotes a more modular and maintainable code structure.
  • It enables the implementation of progressive enhancement, where basic functionality is available to all users, and more advanced features are added for users with JavaScript-enabled browsers.

So, in this article, we will teach you How to run PHP function via JS using Ajax in WordPress without using plugins. 

Step 1. Enqueue localized Ajax call in function.php

   
function theme_name_scripts() {    
wp_localize_script(
        'theme_name-scripts', 'context_object', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        )
    );
add_action('wp_enqueue_scripts', 'theme_name_scripts', 10000);

Step 2. Make a PHP function that you need to execute in function.php

function theme_name_migrate_value( ) {
    // entry here any of your function for ajax request
    set_theme_mod('theme_name_datamigration_status',1);
}
add_action( 'wp_ajax_theme_name_migrate_value', 'theme_name_migrate_value' );

Step 3. Now add a button in customizer upon click will execute above PHP function.

$wp_customize->add_section(
    'theme_name_import_data',
    array(
    'title'     => __('Import Data', 'theme_name'),
    'priority'  => 1,
    ) 
);

$wp_customize->add_control( 'theme_name_import_button', array(
    'type' => 'button',
    'settings' => array(),
    'priority' => 10,
    'section' => 'theme_name_import_data',
    'input_attrs' => array(
        'value' => __( 'Import Data', 'theme_name' ),
        'class' => 'button button-primary',
    ),
) );

Step 4. Create ajax in JS related code that triggers when the above button is clicked and runs the PHP function in any file, such as customizer-click.js.

jQuery(document).ready(
    function () {
wp.customize.control('theme_name_import_button', function (control) {
            control.container.find('.button').on('click', function () {
                jQuery.ajax({
                    type: 'POST',
                    url: ajaxurl,
                    data: {
                        action: 'theme_name_migrate_value',
                    },

                });
            });
        });
    }
);

Step 5. Enqueue file customizer-click.js in customizer.php

function theme_name_customize_backend_scripts()
{
    wp_enqueue_script('theme-name-customizer-click', get_template_directory_uri() . '/assets/customizer/customizer-click.js', array( 'jquery'), '1.1.2', true);
  }
add_action('customize_controls_enqueue_scripts', 'theme_name_customize_backend_scripts', 10);

Below is the example from Context blog pro

PHP function via JS using Ajax

Conclusion:-

If you are able to implement above codes in your theme, you will definitely run PHP function via JS using Ajax in WordPress without using any plugins. If need support then you can contact us. We will here to support you. Meanwhile you can see some of our cool free themes here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link