Wednesday, November 12, 2025

#6 Module 6: AJAX in Plugins (Dynamic Data Handling)

WordPress Plugin Tutorial – Module 6: AJAX in Plugins

🧩 Module 6: AJAX in Plugins (Dynamic Data Handling)

AJAX allows your plugin to fetch or update data without reloading the page. In this module, we’ll build a small example where a button loads a message from the server asynchronously.

Step 1 – Enqueue Script and Add a Button

(📋 You can copy or edit directly below)

    
function mfp_enqueue_ajax_script() { wp_enqueue_script( 'mfp-ajax-script', plugin_dir_url(__FILE__) . 'mfp-ajax.js', array('jquery'), '1.0', true ); wp_localize_script('mfp-ajax-script', 'mfp_ajax_obj', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('mfp_ajax_nonce') )); } add_action('wp_enqueue_scripts', 'mfp_enqueue_ajax_script'); function mfp_display_ajax_button() { echo '<div style="text-align:center;margin:20px;"> <button id="mfp-ajax-btn" style="padding:10px 20px;background:#00d4ff;color:#000;border:none;border-radius:6px;cursor:pointer;"> Load Message via AJAX </button> <div id="mfp-ajax-result" style="margin-top:15px;color:#00ffa3;"></div> </div>'; } add_action('wp_footer', 'mfp_display_ajax_button');

Step 2 – Handle AJAX Request (PHP)

    
add_action('wp_ajax_mfp_get_message', 'mfp_get_message_callback'); add_action('wp_ajax_nopriv_mfp_get_message', 'mfp_get_message_callback'); function mfp_get_message_callback() { check_ajax_referer('mfp_ajax_nonce', 'nonce'); wp_send_json_success('AJAX works! 🎉 This data came from PHP.'); }

Step 3 – Create JavaScript File (mfp-ajax.js)

    
jQuery(document).ready(function($) { $('#mfp-ajax-btn').on('click', function() { $('#mfp-ajax-result').text('Loading...'); $.post(mfp_ajax_obj.ajax_url, { action: 'mfp_get_message', nonce: mfp_ajax_obj.nonce }, function(response) { if (response.success) { $('#mfp-ajax-result').text(response.data); } else { $('#mfp-ajax-result').text('Error occurred.'); } }); }); });
✅ Code copied to clipboard!
© 2025 WordPress Plugin Tutorial | Module 6 – AJAX Example with Prism.js

No comments:

Post a Comment

Welcome to RMC online Tutorials

WordPress Plugin Development – Full Course Index WordPress Plugin Development 12-Module Learning Portal Mod...