1

I'm working an Ajaxifying form. This form is a custom page template. The saving of the data is working, but when the form is submitting, the page is redirects to websiteurl/wp-admin/admin-ajax.php with a white blank page. What I want is to prevent the reloading of the page. I didn't receive any error message from error function.

How to fix this?

HTML

<form method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>" id="modal-form-ajax" autocomplete="off">
        <input type="hidden" name="form_title" value="Resume"/>
        <input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required data-selectable="true">
        <input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required data-selectable="true">
        <input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required data-selectable="true">
        <input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" oninvalid="this.setCustomValidity('Please enter your 11-digits Philippine mobile number')" onchange="try{ setCustomValidity('') } catch(e){}" required data-selectable="true">
        <div class="flex">
            <label>Upload CV & Cover Letter</label>
            <input placeholder="CV" type="file" name="Resume" value="" required>
        </div>
        <input type="hidden" name="action" value="validate_form_modal"/>
        <?php wp_nonce_field('validate_form_modal_nonce', 'name_of_nonce_field'); ?>
        <button id="submit-btn">Submit</button>
    </form>

JS

(function($){
    $("#modal-form-ajax").submit(function(e){
        e.preventDefault();
        var resumetest = $('input[name="form_title"]').val();
        var lastName = $('input[name="lastName"]').val();
        var firstName = $('input[name="firstName"]').val();
        var Email = $('input[name="Email"]').val();
        var contactNumber = $('input[name="contactNumber"]').val();
        var ajaxUrl = { ajaxFormUrl: '//websiteurl/wp-admin/admin-ajax.php' }
          $.ajax({
            type: 'post',
            dataType: "json",
            url: ajaxUrl.ajaxFormUrl,
            data: {
                action: 'validate_form_modal',
                lastName: lastName,
                firstName: firstName,
                Email: Email,
                contactNumber: contactNumber,
                Resume: Resume
            },
            success: function(data){
                console.log("Thank you for your application");
                console.log($('#modal-form-ajax').serialize());
                $("#modal-form-ajax").fadeOut('ease',function(){
                  $("#modal-form-ajax").html('<div id="modal-form-success"><div class="circle-loader"><div class="checkmark draw"></div></div><p>Thank you for your application</p><p>We\'ll get back to you shortly.</p></div>');
                  $("#modal-form-ajax").fadeIn('ease');
                });
              },
            error: function(){
                alert(response);
            }
          });
    });
})(jQuery);

PHP (functions.php)

function ajax_modal_form_init(){
    wp_localize_script('ajax-modal-form', 'modalFormAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
    wp_enqueue_script('ajax-modal-form');
}

add_action('wp_ajax_validate_form_modal', 'validate_form_modal');
add_action('wp_ajax_nopriv_validate_form_modal', 'validate_form_modal');
function validate_form_modal(){
    ob_clean();
    global $wpdb;

    if(!isset($_POST['name_of_nonce_field']) || ! wp_verify_nonce( $_POST['name_of_nonce_field'], 'validate_form_modal_nonce')){
        exit('The form is not valid');
    }

    $lastName               = isset($_POST['lastName']) ? filter_var($_POST['lastName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) : '';
    $firstName              = isset($_POST['firstName']) ? filter_var($_POST['firstName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) : '';
    $email                  = isset($_POST['Email']) ? filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL) : '';
    $contactNumber          = isset($_POST['contactNumber']) ? filter_var($_POST['contactNumber'], FILTER_VALIDATE_REGEXP) : '';

    echo do_shortcode("[cfdb-save-form-post]");

    wp_die();
}
4
  • The script isn't running at all, how are you loading it? Feb 2 '18 at 10:59
  • the js script is written in one page with the html (custom page template)
    – indigo
    Feb 2 '18 at 11:19
  • @JacobPeattie, I already to separate the js script but still same issue
    – indigo
    Feb 2 '18 at 11:41
  • The only thing I can think of is that the way you have your AJAX URL structured is different than anything I've seen before. I normally just use: var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>'; - not sure if that'll change anything but since the page is redirecting to the url after success maybe that's part of it? Nov 30 '20 at 20:40
1

Just saw it... ...in your HTML, take the action out entirely. We're not using the HTML to tell the form/submit button what to do, we're using JS/AJAX for that.

<form method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>" id="modal-form-ajax" autocomplete="off">

Should become:

<form method="POST" id="modal-form-ajax" autocomplete="off">

Also, instead of targeting the form, target the submit button, so the following:

$("#modal-form-ajax").submit(function(e){
     e.preventDefault();

Should become:

$("#submit-btn").on('click',function(e) {
     e.preventDefault();
0

Try one of these:

  1. Put the submit button outside the form and bind the js-function to the button instead $('#submit-btn).on('click', function(e){ e.preventDefault(); ...}).
  2. Try to return false; and the end of your script, right after $.ajax({...});.

Read more in this SO question.

2
  • I tried to put the button tag outside the form. The form is not now refreshing after submit, but the form data is not saving and the success fuction is not display
    – indigo
    Feb 5 '18 at 3:17
  • I also followed the solution in the link that you provided, but still no luck :(
    – indigo
    Feb 5 '18 at 10:20

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.