Custom Form with Ajax

Your attempt to send your AJAX requests to wp-admin/admin-ajax.php is correct but it will be better to create a javascript global variable using wp_localize_script() to make any data available to your script in functions.php that you can normally only get from the server side of WordPress.

For example, your javascript code can be in the same folder with functions.php as such:

[Theme Folder]

–>functions.php

–>js [folder] –> makebooking.js

Your jquery in makebooking.js should look like this:

jQuery(document).ready(function(event) {

 jQuery('#BookingForm').submit(ajaxSubmit);

 function ajaxSubmit() {
    var BookingForm = jQuery(this).serialize();
    jQuery.ajax({
      action:  'make_booking',
      type:    "POST",
      url:     MBAjax.admin_url,
      data:    BookingForm,
      success: function(data) {
         jQuery("#feedback").html(data);
      }
    });
    return false;
  }
});

With makeBooking() processing the data, add the following at the top your functions.php:

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'make-booking-ajax','js/makebooking.js', array( 'jquery' ) );

// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

add_action('wp_ajax_make_booking', 'makeBooking');

For more reference, have a look at 5 Tips for using Ajax in WordPress

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)