The very first thing to enable Ajax popup is to enqueue script. Then we need to add ajax url so that we can access admin ajax url in JavaScript File. To do this, here we are using wp_localize_script() function. We have used wp localize script() function to translate the Admin Ajax url into JavaScript file. The result looks like this:
/**
* Add javascript file to handle ajax call and add ajax url
*/
function my_load_scripts($hook) {
wp_enqueue_script( 'lb-ajax-handler', get_stylesheet_directory_uri() . '/assets/js/ft-ajax.js', array( 'jquery' ),1.0,true );
wp_localize_script( 'lb-ajax-handler', 'ajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
Next things is to add javascript code to in ft-ajax.js file. You can find the code below how Ajax works.
// ajax function jQuery
jQuery(document).ready(function() {
jQuery('#product-offer').click(function(event) {
/* Act on the event */
var product_id = event.target.getAttribute('data-id');
jQuery.ajax( {
url: ajax.url,
type:'POST',
data: {
action: 'do_some_php_code',
product_id: product_id,
},
success: function( data ) {
// On a succesful return 'data' contains whatever you have echoed in the ajax function
//console.log( data );
if(data) {
elementorProFrontend.modules.popup.showPopup( { id: 19 } );
jQuery('#popup-product-name .elementor-heading-title').text(data);
}
}
});
});
});
Finally add Ajax function to handle variables sent by jQuery Ajax and do some programming and echo or print the value after getting data from WordPress backend.
//ajax function for wordpress
function do_some_php_code() {
$product_name = get_the_title($_POST['product_id']);
echo $product_name;
if ( wp_doing_ajax() ) {
exit;
}
}
add_action('wp_ajax_nopriv_do_some_php_code','do_some_php_code');
add_action('wp_ajax_do_some_php_code','do_some_php_code');