Support » Developing with WordPress » Multiple AJAX Callback functions

  • Resolved gshell

    (@gshell)


    Can I have multiple AJAX callback functions within the same plugin?

    I have created a plugin that allows members to register or cancel registrations to an event created with the Events Calendar plugin (Tribe Events). The rsvp_callback function is activated via various button clicks and works properly. I then created a eventid_callback function to send the eventid parsed from the specific event page being viewed to the server side. This function creates an error in the console that states:

    HTTP400: BAD REQUEST – The request could not be processed by the server due to invalid syntax.

    I have gone through the code dozens of times and do not see what I have wrong other than possibly I can not do what I am trying to do.

    I enqueued the JS file and the ajax url at the top of the plugin as follows:

    add_action( 'wp_enqueue_scripts', 'event_rsvp_enqueue_scripts' );
    function event_rsvp_enqueue_scripts() {
    
    	wp_enqueue_script( 'rsvp', plugins_url( '/js/rsvp.js', __FILE__ ), array('jquery'), '1.0', true );
    
    	wp_localize_script( 'rsvp', 'ajax_rsvp', array(
    		'ajax_url' => admin_url( 'admin-ajax.php' )
    	));
    };
    

    The JS code for the eventid_callback is (note that I used the same AJAX URL for both functions which is a concern that I can not do that). The alert properly displays the parsed event_id just prior to the AJAX call:

    	if($jq("#tribe-events-content").hasClass("tribe-events-single")) {
    		// alert ("on single event page");
    		$jq(".tribe-events-nav-pagination").hide();
    		var event_category = ($jq( ".tribe-events-event-categories" ).text());
    		// alert ("Event Category is " + event_category);
    		var event_start = ($jq( ".tribe-events-start-date" ).attr("title"));
    		// alert ("Event Start Date is " + event_start);
    		var event_id = event_category.substring(0,1) + event_start.substring(0,4) + event_start.substring(5,7) + event_start.substring(8,10);
    		alert ("Event ID is " + event_id);
    
    		$jq.ajax({
    			url : ajax_rsvp.ajax_url,
    			type : 'post',
    			data : {
    				action: 'eventid_callback',
    				event_id_name : event_id
    			},
    			success:function(data) {
    				// This outputs the result of the ajax request
    				console.log(data);
    				// Return response to client side
    				$jq('#rsvp_response').html( data );
    				return false;
    			},
    			error: function(errorThrown){
    				console.log(errorThrown);
    			}
    		}); // End of AJAX function
    	};
    

    The eventid_callback function is:

    add_action( 'wp_ajax_eventid_callback', 'eventid_callback' );
    
    function eventid_callback() {
    	$event_id = $_POST[event_id_name];
    	echo "<p>Event ID from eventid_callback is: {$event_id} </p>";
    }; // end of eventid_callback function
    

    The echo does not return any values. One other issue that I don’t fully understand is the first parameter of the add_action statement. Every example I have seen simply appends ‘wp_ajax_’ in front of every callback function name that you decide to use. I don’t understand what that first variable represents.

    Any comments or suggestions would be appreciated.
    Thanks

Viewing 7 replies - 1 through 7 (of 7 total)
  • The first argument of add_action is the hook name. The 2nd argument is the function to run on that hook. When you send request to admin-ajax.php WordPress executes a hook with the name wp_ajax_ and then whatever the action parameter send with the request is named.

    So in your example, you are sending this data to admin-ajax.php:

    data : {
    	action: 'eventid_callback',
    	event_id_name : event_id
    },
    

    In that example the action is eventid_callback, so when WordPress receives the request it runs the wp_ajax_eventid_callback action.

    When you use add_action() with that hook name, it lets you run a function in response to AJAX requests with the associated action name.

    So to handle AJAX requests you need to create an action for each type of request you want to handle, then in your JavaScript you need to name that action as part of the request.

    The one thing you’re missing is that the wp_ajax_ hook only runs for logged in users. For logged-out users WordPress has a separate hook. It’s the same idea, but the prefix is wp_ajax_nopriv_.

    So if you want your AJAX to work for logged out and logged in users you need to use both hooks:

    add_action( 'wp_ajax_eventid_callback', 'eventid_callback' );
    add_action( 'wp_ajax_nopriv_eventid_callback', 'eventid_callback' );
    
    gshell

    (@gshell)

    Thanks Jacob, That makes sense and I understand the hook process better.

    In my case, the calls should always be executed only when a user is logged in, so I don’t see a need for the nopriv hook. In fact, if this routine were to be executed by someone that was not logged in, it should return an error and exit.

    I still don’t understand why I am getting the HTTP400 BAD REQUEST error. Can I use the same AJAX URL (ajax_rsvp.ajax_url), for two separate callback functions (eventid_callback, and rsvp_callback) or do I need to have unique urls for each AJAX exchange?

    Moderator bcworkz

    (@bcworkz)

    admin-ajax.php can handle all the callback functions you care to add. It’s little more than an elaborate switch(){} structure that routes requests to the right callback. Multiple callbacks is actually what it’s set up to handle and why an action value is required.

    Your Ajax handler callback needs to exit(), die() or otherwise terminate the process. Otherwise PHP tries to return flow to the caller, which is entirely unexpected and the cause of the error.

    gshell

    (@gshell)

    Hi bcworkz,
    I should have caught the omission of the die() in the callback function. I added it and it made no difference.
    Does an AJAX call require a button or input function in order to work? All examples of an AJAX call seem to have a Submit button that fires it. In my case at this time, I added the call to extract information about the page immediately on page load IF the page has the proper ID and Class.

    Josh

    (@josh401)

    You don’t need a button or input function. You can execute the ajax from any jquery action. You also don’t need different action names. You can use the same action multiple times; as long as you’re getting the data you need on the php side.

    1) Console log your ajax_rsvp.ajax_url javascript variable and make sure you are getting the correct site url before executing your ajax call.

    2) Change the order of how you are localizing your script from php:

    
    wp_register_script( 'rsvp', plugins_url( '/js/rsvp.js', __FILE__ ) );
    wp_localize_script( 'rsvp', 'ajax_rsvp', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_script( 'rsvp' );
    

    Use that order; register, then localize, then enqueue.

    • This reply was modified 1 year ago by Josh.
    • This reply was modified 1 year ago by Josh.
    gshell

    (@gshell)

    Josh,
    Thanks, I tried that sequence, but it made no change.

    What do you mean by your item 1)? I have included a JS Alert box with the variable displayed immediately before the ajax call. Is there something else I could do? I am looking for more methods to debug the ajax process as I still have trouble with it as you can tell.

    What I am confused about is that if I change the action line in the JS file from:

    			data : {
    				action: 'rsvp_callback',
    				event_id_name : event_id
    			},
    

    To:

    			data : {
    				action: 'eventid_callback',
    				event_id_name : event_id
    			},
    

    I get an error in the console log of:

    HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
    (XHR)POST - http://localhost:81/wordpress/wp-admin/admin-ajax.php

    When using the rsvp_callback function the AJAX call works fine although that function does things that I do not want to do all of the time.

    The code for the eventid_callback function is pretty simple and I don’t see what I have wrong.

    add_action( 'wp_ajax_eventid_callback', 'eventid_callback' );
    function eventid_callback() {
    	$event_id = $_POST[event_id_name];
    	echo "<p>Event ID from eventid_callback is: {$event_id} </p>";
    	die();
    }; // end of eventid_callback function
    
    gshell

    (@gshell)

    I think I found the problem.

    I had included the new eventi_id callback inside another function of the plugin, when I moved it outside of that function into the main plugin code, it worked properly.

    Thanks to all that helped me out.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Multiple AJAX Callback functions’ is closed to new replies.