mdvaldosta mdvaldosta - 3 months ago 16
Ajax Question

Wordpress Frontend Simple Ajax Form Not Working

For several hours I've been unable to figure this out. I'm fairly green with Ajax, and I hope I'm just missing something obvious. Please save my hair!

In functions.php

// Quote box
function ajax_quotebox_init(){

wp_register_script('ajax-quotebox-script', get_template_directory_uri() . '/ajax-quotebox-script.js', array('jquery') );
wp_enqueue_script('ajax-quotebox-script');

wp_localize_script( 'ajax-quotebox-script', 'ajax_quotebox_object', array(
'ajaxurl' => home_url( 'wp-admin/admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Processing, please wait...')
));

// Enable the user with no privileges to run ajax_quotebox() in AJAX
add_action( 'wp_ajax_nopriv_ajax_quotebox', 'ajax_quotebox' );
}
add_action('init', 'ajax_quotebox_init');

function ajax_quotebox() {

// First check the nonce, if it fails the function will break
//check_ajax_referer( 'ajax-quotebox-nonce', 'security' );

$first_name = sanitize_text_field($_POST['first_name']);
$last_name = sanitize_text_field($_POST['last_name']);
$vehicle = sanitize_text_field($_POST['vehicle']);
$phone = sanitize_text_field($_POST['phone']);
$zip = sanitize_text_field($_POST['zip']);

// Nonce is checked?? get the POST data and sign user on
if ($first_name !== 'Joe'){
echo json_encode(array('message'=>__('Did not get "Joe" for first_name')));
} else {
echo json_encode(array('message'=>__('Form successful, redirecting...')));
}

die();
}


the form:

<div class="quotebox-container">
<h3 class="wow animate bounceIn">Get <span>Ca$h</span> Now!</h3>
<hr>
<form id="quotebox" action="quotebox" method="post">

<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="first_name" id="first_name" class="form-control input-sm" placeholder="First Name">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="last_name" id="last_name" class="form-control input-sm" placeholder="Last Name">
</div>
</div>
</div>

<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<input type="text" name="vehicle" id="vehicle" class="form-control input-sm" placeholder="Vehicle (ex: 2009 Honda Civic EX)">
</div>
</div>
</div>

<div class="row">
<div class="col-xs-7 col-sm-7 col-md-7">
<div class="form-group">
<input type="text" name="phone" id="phone" class="form-control input-sm" placeholder="Phone Number">
</div>
</div>
<div class="col-xs-5 col-sm-5 col-md-5">
<div class="form-group">
<input type="text" name="zip" id="zip" class="form-control input-sm" placeholder="Zip Code">
</div>
</div>
</div>

<button type="submit" id="submit" name="submit" class="btn btn-primary btn-lg btn-block c-btn-square quote quotebox-submit" data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Processing"><i class="fa fa-hand-o-right wow animate fadeIn"></i> Tell Me How Much</button>

<p class="status"></p>

<?php wp_nonce_field('ajax-quotebox-nonce', 'security') ?>

</form>

<div class="quote-help">
We'll contact you promptly with an amazing quote!
</div>
</div>


in ajax-quotebox-script.js

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

// Perform AJAX quotebox action on form submit
$('form#quotebox').on('submit', function(e){
$('form#quotebox p.status').show().text(ajax_quotebox_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_quotebox_object.ajaxurl,
data: {
'action': 'ajax_quotebox', //calls wp_ajax_nopriv_quote_box
'first_name': $('#first_name').val(),
'last_name': $('#last_name').val(),
'vehicle': $('#vehicle').val(),
'phone': $('#phone').val(),
'zip': $('#zip').val(),
'security': $('form#quotebox #security').val() },
success: function(data){
$('p.status').text(data.message);
$('.submit').button('reset');
}
});
e.preventDefault();
});

});


the only data I'm getting from the form:

action:ajax_quotebox
first_name:
last_name:
vehicle:
phone:
zip:
security:fcf393d8d8

Answer

The e.preventDefault(); should be at the top of the function like this:

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

    // Perform AJAX quotebox action on form submit
    $('form#quotebox').on('submit', function(e){
        //At the top to prevent the default action before the form data is parsed.
        e.preventDefault();

        $('form#quotebox p.status').show().text(ajax_quotebox_object.loadingmessage);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_quotebox_object.ajaxurl,
            data: { 
                'action': 'ajax_quotebox', //calls wp_ajax_nopriv_quote_box
                'first_name': $('#first_name').val(), 
                'last_name': $('#last_name').val(), 
                'vehicle': $('#vehicle').val(),
                'phone': $('#phone').val(),
                'zip': $('#zip').val(),
                'security': $('form#quotebox #security').val() },
            success: function(data){
                $('p.status').text(data.message);
                $('.submit').button('reset');
            }
        });
    });
});

You could also change the button type to just "button" since we don't need the submit action but that might not be valid or best practice for accessibility even though it will work.

EDIT I looked at your page source and you have multiple inputs with id="first_name". You can't have an ID in multiple locations. The additional fields with the same IDs appear to be in a modal but since they have the same ID it will still cause confusion. This applies to all the fields.