2

It seems that I miss out some basic concept of jquery, since this script won't do what I want it to do:

    $(document).ready(function(){

    $('#form').submit(function(event) {
    console.log( "submitted form, checking #domain_url_input ");
    // event.preventDefault(); 
    var submit_error=false; 
    var is_primary_url = false;
    var url = $('#domain_url_input').val();

    var get_url = '/i.php?a=check&url2check=' + escape(url);
    var valid_data = $.ajax({
        event: event,
        url: get_url,
        success: function(response) {
            // alert('ajax successful'); 
            is_primary_url = $(response).find('#check_div').text(); 
            // alert(is_primary_url);

            var dns_zone    = $('#dns_zone_sel').val(); 

            if (is_primary_url == 'YES' && dns_zone=='') 
                { 
                event.preventDefault();
                alert('Choosing a DNS ZONE is required!');
                $('#dns_zone_sel').focus(); 
                this.submit_error=true; 
                // if (submit_error==true) event.preventDefault(); 
                // return 'error'; 
                } // 

            } // end func success
        }); // ajax  

    }); // submit

    }); // rdy

(I reduced the code a bit of course.)

The code works perfectly, except for the:

event.preventDefault();

won't take effect.

IF i put it into the second line right after

$('#form').submit(function(event) {...

it will work though.

The ajax-call works, I get a positive result. It is as if it would not be possible to PREVENT the SUBMIT any more?

The Alert after:

event.preventDefault(); alert('Choosing a DNS ZONE is required!');

works perfectly, meaning, the script works, except for that the preventDefault() does not have an effect. That may be due to the event "event" to which I don't have proper access?

The intent is:

I want to stop the submit event. I older js scripts I did that via "return false;" but that won't work either. Btw: I know the difference between preventDefault() and "return false",... I am just adding the information that I tried. In this case the "return false" would return from the $(...).ajax() to the $(...).submit() event.

Point is: the form submit() is already in progress when the $().ajax part is still doing the request. So somehow I need to make the submit() wait until the ajax is finished?

Thanx for any ideas!

AFTER ALL THIS following SOLUTION WORKS excactly how I wished - Thanks to my friend Andreas, @Cory and @Michael:

`<script type="text/javascript">
$(document).ready(function(){
var disableSubmit   = false;
var transmitNow     = false;
$('#form').submit(function(event) {
    console.log( "submitted form, checking #domain_url_input ");
    console.log( "disableSubmit=" + disableSubmit); 
    if( transmitNow === true ) return;  
    event.preventDefault(); 
    if (disableSubmit ===true) return; 
    $('#form').prop( 'disabled', true );
    var submit_error=false; 
    var is_primary_url = false;
    var url = $('#domain_url_input').val();
    if (url=='') { alert('Error! A domain/url must be provided!'); return false; } 

    var get_url = '/i.php?a=check&ajax=1&url2check=' 
                        + escape(url) + '&t='+ Date.now();

    disableSubmit   = true; // Formular ausgrauen .... als todo 
    var valid_data = $.ajax({
        url: get_url,
        error: function(){ disableSubmit = false; $('#form').prop( 'disabled', false ); },
        complete: function(){ disableSubmit = false; $('#form').prop( 'disabled', false ); },
        success: function(response) {
            disableSubmit = false; 
            $('#form').prop( 'disabled', false );

            is_primary_url = $(response).find('#is_url_primary_check_div').text(); 

            var registrar   = $('hd[registrar]').val(); 
            var webserver   = $('hd[webserver]').val(); 
            var dns_zone    = $('#dns_zone_sel').val(); 

            if (is_primary_url == 'YES' && dns_zone=='') 
                { 
                // event.preventDefault();
                alert('You entered a primary domain. Choosing a DNS ZONE is required!');
                $('#dns_zone_sel').focus(); 
                submit_error=true; 
                }   
            if (submit_error != true ) 
                { 
                transmitNow = true; 
                $('#form').submit();
                }  
            } // end event func success
        }); // ajax  

    }); // submit

}); // rdy
    </script>`

THANX TO ALL!! :) happy!

2
  • 1
    Where is event_submit defined? It's first usage is you calling preventDefault() on it. If it's null or undefined then it certainly won't work. Also, AJAX is asynchronous. Your submit event is completing long before the success callback of your AJAX call, which is why it doesn't work there. Commented Aug 21, 2016 at 18:23
  • hi, :) -- yes, I changed the script in order to present is here: "event_submit" is defined, I shortened is here to "event" and forgot to change it in the comments, etc. in the original script the name of the event is event_submit in all cases, so that s not the problem, sorry for the irritation. Thanx for the explanation / confirmation of the asynchronosity. Commented Aug 21, 2016 at 19:20

2 Answers 2

1

As Cᴏʀʏ explained, your .preventDefault() call isn't working because the form has already been submitted at the time the $.ajax() call completes.

One way to fix this would be to always call .preventDefault() directly in the submit() callback, and then after your validation succeeds, explicitly call submit() with no arguments to submit the form.

In addition, you probably want to disable the form's input fields and submit button while waiting for the Ajax request. This will also allow you to avoid having the submit() callback take any action while you make the explicit submit() call.

A simplified version to illustrate the idea:

var disableSubmit = false;
$('#form').submit( function( event ) {
    event.preventDefault();
    if( disableSubmit ) return;
    disableSubmit = true;
    $('#form input, #form button').prop( 'disabled', true );
    $.ajax({
        ...
        success: function( data ) {
            if( dataIsGood(data) ) {
                $('#form').submit();
                disableSubmit = false;
                $('#form input, #form button').prop( 'disabled', false);
            }
        }
    });
});

There are some error and edge cases not handled here - for example what if you get an error response from the server, or never get a response at all? But this may be a place to start.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanx Michael, i was thinking about this same thing, and not even trying it, since in my logic when sending the "$('#form').submit();" it should call the same function again and again? or not? but i ll try it, right now.
It is as I thought: the script is getting into a LOOP :( - dead end ;(
@user3745627: I should have thought of that! Should be easy to fix though, see my update to the answer. The added code should both prevent the recursion and will disable the form submittal while waiting for the Ajax request.
wonderful: I was just wondering if/how i could do what you described here using this : var disableSubmit = false; $('#form').submit( function( event ) { event.preventDefault(); if( disableSubmit ) return; disableSubmit = true; .... This might work out :) coool
@lps: That's a good point, a simple focused answer is a good thing and the added code made it more complex. The problem was that the first version was completely broken: It resulted in infinite recursion when the .submit() call triggered another submit event.
|
0

It is problematic to mix using the built-in form mechanism with an ajax request. If you want to use ajax to submit the form, the leave the preventDefault() when the form is submitted, then do your form validation, and if it passes do a $('#form').submit() manually.

Alternatively, you can remove the submit button from the form and replace it with a regular button and capture the "submit" on $('#form_submit_button').click(), then submit the form manually if validation passes.

Basic example of the latter approach:

HTML:

<form id="form" onSubmit="validate_Form();return false">
    //form fields...no submit-type button
    <button id="form_submit_button">
</form>

JS:

$("#form_submit_button").click(function() {
    if(validate_form()) { //put your ajax code in the validate_form() method
        $("#form").submit();
    }
});

Edit:

As @Michael_Geary pointed out, the latter approach is not great because a user can hit the Enter button to submit the form so if you want to use that option you'd have to capture the Enter press and stop it from submitting the form...you could use the accepted answer in this question: Capture the enter key cross-browser, my solution isn't working, but that would affect the entire page and is a bit convoluted. So the first approach is best.

3 Comments

Removing the submit button wouldn't prevent the form from being submitted. The user could still hit the Enter key from an input field.
excactly, my very same thought
OK, updated my answer for thoroughness. @MichaelGeary's answer/the first approach I mentioned is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.