Problem coding AJAX in WordPress Plugin
-
Hi guy’s, banging my head against a wall here trying to get AJAX to work in a wordpress plugin that I am writing. Any help would be massively appreciated!
Thanks in advance,
SeanHere is where I am at –
Below is an excerpt from my main plugin file where I register the JavaScript file I use to make the ajax call and set up my ajax handle. My understanding is the wp_localize_script should pull the PHP file I use to process the ajax request in to the wordpress fold and allow it access all the WordPress functions. This is where I think my issue lies.
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' ); function so_enqueue_scripts(){ wp_register_script( 'ajaxHandle', plugins_url() . '/custom-registration/js/call_ajax.js', array('jquery'), false, true ); wp_enqueue_script( 'ajaxHandle' ); // Localise the PHP script that will handle the AJAX request wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => plugins_url( 'custom-registration/process-ajax.php' ) ) ); }Below is the JS file that makes the call –
/custom-registration/js/call_ajax.jsjQuery(document).ready( function($){ $('form.billing-form').submit(function(event) { event.preventDefault(); var data = { action: 'my_ajax_action', name: 'my name', message: 'my message' } $.ajax({ url: ajax_object.ajaxurl, type:"POST", data: data, success: function( data ) { alert( 'AJAX Success'); }, error: function( ) { alert( 'AJAX failed'); } }) });Here is my PHP file that should process the request –
/custom-registration/process-ajax.phpadd_action('wp_ajax_my_ajax_action', 'my_ajax_action_callback'); function my_ajax_action_callback() { echo 'It works!'; wp_die(); }The PHP file gets hit but a fatal error is thrown because –
PHP LOG
Call to undefined function add_action()add_action() is a wordpress function and my process-ajax.php mustn’t be wired up correctly to access the WP functionality.
The topic ‘Problem coding AJAX in WordPress Plugin’ is closed to new replies.