4

I am having problems with my form. When the submit button is clicked a 404 error is spit out. If anyone has any suggestions I'd be grateful.

Ajax handling of form. Going into theme's js.

<script type="text/javascript">
    jQuery('#BookingForm').submit(ajaxSubmit);

    function ajaxSubmit(){
        var BookingForm = jQuery(this).serialize();
        jQuery.ajax({
            action : 'make_booking',
            type   : "POST",
            url    : "/wp-admin/admin-ajax.php",
            data   : BookingForm,
            success: function(data){
                jQuery("#feedback").html(data);
            }
        });
        return false;
    }
</script>

PHP going into functions.php

function makeBooking(){
    global $wpdb;

    $type   = $_POST["optionsRadios"];
    $to     = $_POST["to"];
    $from   = $_POST["from"];
    $date   = $_POST["date"];
    $time   = $_POST["time"];
    $name   = $_POST["name"];
    $tel    = $_POST["tel"];
    $email  = $_POST["email"];
    $passenger = $_POST["optionsRadios2"];
    $other  = $_POST["other"];

    if( $wpdb->insert('Booking',
      array(
        'type'=>$type,
        'from1'=>$from,
        'to1'=>$to,
        'date'=>$date,
        'time'=>$time,
        'name'=>$name,
        'tel'=>$tel,
        'email'=>$email,
        'passenger'=>$passenger,
        'other'=>$other
      )
    ) === FALSE ) {
        echo "Error";
    }
    else {
        echo "Submission successful, an email receipt has been sent to your email address.       
        <br> Your Booking ID is:<b>ZCA- ".$wpdb->reference . "</b>";

        //Prepare email body
        $msg = "Reference: ZCA-" . $reference . "\nType:" . $type . "\nFrom:" . $from .     "\nTo:" . $to . "\nDate" . $date . "\nTime:" . $time . "\nName:" . $name . "\nNumber:" .     $tel . "\nEmail:" . $email . "\nPassengers:" . $passenger . "\nOther:" . $other;
        mail("taxi@zcarsglobal.com","Booking",$msg);
        mail($email,"Zcars Global Booking","Thank you for your enquiry. We aim to deal with your request straight away." . $msg);

    }
    die();
}
add_action('wp_ajax_make_booking', 'makeBooking');
add_action('wp_ajax_nopriv_make_booking', 'makeBooking'); // not really needed

I am including the HTML form as I am still getting the 404 error, maybe it's something here?

<form method="post" id="BookingForm">

  <div class="radio">
    <label>
      <input type="radio" name="optionsRadios" id="booking" value="booking" checked>
        Booking
    </label>
  </div>

<div class="radio">
  <label>
    <input type="radio" name="optionsRadios" id="quotation" value="quotation">
    Quotation
  </label>
</div>

  <div class="form-group">
    <label for="from">From *</label>
    <input name="from" id="from" type="text" class="form-control" placeholder="Where are you?" required>
  </div>
  <div class="form-group">
     <label for="to">Going to *</label>
    <input name="to" id="to" type="text" class="form-control" placeholder="Where are you going to?" required>
  </div>
  <div class="form-group">
     <label for="date">Date *</label>
    <input name="date" id="date" type="date" class="form-control"  required min="<?php echo date("dd-mm-yyyy"); ?>">
  </div>
    <div class="form-group">
     <label for="time">Time *</label>
    <input name="time" id="time" type="time" class="form-control"  required>
  </div>
  <div class="form-group">
    <label for="name">Name *</label>
    <input name="name" id="name" type="text" class="form-control" placeholder="What is your name?" required>
  </div>
    <div class="form-group">
    <label for="tel">Telephone Number *</label>
    <input name="tel" id="tel" type="number" class="form-control" placeholder="What is your number?" required>
  </div>
  <div class="form-group">
    <label for="email">Email *</label>
    <input name="email" id="email" type="email" class="form-control" placeholder="What is your email?" required>
  </div>

  <h4>Passengers</h4>
  <div class="radio">
    <label>
      <input type="radio" name="optionsRadios2" id="4orless" value="1to4" checked>
        4 or Less
    </label>
  </div>
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios2" id="4to6" value="4to6">
    4 to 6
  </label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="optionsRadios2" id="6to8" value="6to8">
    6 to 8
  </label>
</div>
<textarea name="other" class="form-control" rows="3">Please write here anything else we need to know</textarea>
 <input type="hidden" name="action" value="makeBooking"/>
  <input type="submit">
</form>





  • 2
    there is no action argument for ajax, that should be part of data. – Milo Apr 23 '15 at 16:58
7

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

  • Hi there, thanks for your amazing reply! I am no longer getting a 404, but a blank page on submit. Or once I got the html of the entire page inside the #feedback div. – raikkonen Apr 23 '15 at 19:52
  • from your php code, you do not have any xhr response. After sending the mail try echo "Thanks for booking" and replace die() with exit;. By the way, you have not defined $reference anywhere in your code. Lastly, check your php_error.log file for details. – CeganB Apr 24 '15 at 7:25
  • Isn't the echo just before the mail send sufficient? Thanks for the $reference, fixed that. Hmm php_error.log doesn't show any errors in the last few days. This is baffling. – raikkonen Apr 24 '15 at 22:03
  • hi, why are you calling MBAjax.BookingForm, there's no member like that. its just a var. – pcarvalho Jun 30 '16 at 21:17
0

You cannot use Ajax on Wordpress that way. There are many tutorial about using Ajax on wordpress. I think the simplest is http://natko.com/wordpress-ajax-login-without-a-plugin-the-right-way/

0
add_action('wp_ajax_make_booking', 'makeBooking');
add_action('wp_ajax_nopriv_make_booking', 'makeBooking'); // not really needed

Put these two lines above the makeBooking function.

Worked for me! Also, see how I'm sending the action in data!

$( "#signupFormTag" ).submit(function( event ) {

              event.preventDefault();

                var signupForm = jQuery(this).serialize();
                jQuery.ajax({
                    // action : 'signup_paragon',
                    type   : "POST",
                    url    : "/paragaon-3/wp-admin/admin-ajax.php",
                    data   : {
                        from: signupForm,
                        action: 'signup_paragon'
                    },
                    success: function(data){
                        console.log(data);
                        //jQuery("#feedback").html(data);
                    }
                });
                // return false;

            });
0
jQuery(document).ready(function($) {

 // Perform AJAX login on form submit
    $('form#login').on('submit', function(e){
        $('form#login p.status').show().text(ajax_login_object.loadingmessage);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_login_object.ajaxurl,
            data: { 
                'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
                'username': $('form#login #username').val(), 
                'password': $('form#login #password').val(), 
                'security': $('form#login #security').val() },
            success: function(data){
                $('form#login p.status').text(data.message);
                if (data.loggedin == true){
                    document.location.href = ajax_login_object.redirecturl;
                }
            }
        });
        e.preventDefault();
    });

});
  • 1
    Can you add an explanation, why could that solve the problem? – nmr Aug 14 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.