• 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,
    Sean

    Here 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.js

    jQuery(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.php

    add_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.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    All WP AJAX calls must be routed through admin-ajax.php. The localize script function only outputs JS assignments in the page head, it has nothing to do with WP PHP functions being available.

    The AJAX request must have an ‘action’ value, which is used to build and apply a dynamic action hook. Your AJAX handler code is added as a callback to this action. More detailed information begins here:
    https://developer.ww.wp.xz.cn/plugins/javascript/
    and continues on to a code summary.

Viewing 1 replies (of 1 total)

The topic ‘Problem coding AJAX in WordPress Plugin’ is closed to new replies.