Prevent page reload after ajax form submission

I’m trying to submit a form in wordpress with ajax. But after the first submision the page itself is called again.

My Form

<form class="et_pb_contact_form clearfix" method="post" action="" id="loginform">
<p class="et_pb_contact_field et_pb_contact_field_0 et_pb_contact_field_last" data-id="mail" data-type="input">
    <label for="et_pb_contact_mail_1" class="et_pb_contact_form_label">E-Mail-Adresse</label>
    <input type="email" name="mail" id="mail" value="" placeholder="E-Mail-Adresse" required=""/>
</p>
<p class="et_pb_contact_field et_pb_contact_field_1 et_pb_contact_field_last" data-id="pw" data-type="input">
    <label for="et_pb_contact_pw_1" class="et_pb_contact_form_label">Passwort</label>
    <input type="password" name="pw" id="pw" value="" placeholder="Passwort" />
</p>
<div class="et_contact_bottom_container">                       
    <button type="submit" class="et_pb_contact_submit et_pb_button">Einloggen</button>
</div>                  

Javascript:

jQuery(document).ready(function() {
    jQuery(document).on('submit', '#loginform' ,function(e) {
        e.preventDefault();
        jQuery.ajax({
            type: "POST",
            url: 'backend_login.php',            
            data: jQuery(this).serialize(),            
            success: function(data) {
                if (data === 'true') {
                    window.location = 'main.php';
                }
                else if (data.indexOf("Fehler") !== -1) {
                    alert(data);
                }
                else {
                    jQuery('#loginnote').fadeIn();
                }
            }
        });
    });
});

If I open the page ([domain]/login) and hit the Submit Button the first two XHR occur of which the first one is correct. But where does the second XHR come from, and how to prevent from this? After the site is new loaded and I hit the submit button again, only the correct and third XHR occur.

enter image description here

2 Answers
2

To solve this, you need to unbind the event that triggers the second AJAX request. You need to make sure that your unbind() function is called after the event binding has occurred.

So why not just load it in the footer? One reason is that the other script that binds the event might be loading in the footer, too.

To control the loading order of scripts, you can actually use the dependencies parameter of wp_enqueue_scripts(). You just need to know the handler of the script that you wish do add as a dependency:

wp_enqueue_script( 'my-handler', 'script.js', array( 'another-script-handler' ) );

my-handler is now depending upon and is therefore loaded after another-script-handler.

Leave a Comment