Multiple AJAX Callback functions
-
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
- The topic ‘Multiple AJAX Callback functions’ is closed to new replies.