0

I am using the 'required' attribute in my form child tags for validation. The problem that I have is that, when I first click submit, no validation takes place and an empty form also gets submitted.

From the second time on wards, each time I click submit the validation check kicks in and reports an empty field.

My code:

<form>
    <label for="id">ID:</label>
    <input type="text" class="form-control"  id="id" required>
    <label for="name">Name:</label>
    <input type="text" class="form-control" id="name" required />
    <button type="submit" class="btn btn-info pull-right"   id="sub">Submit</button>
</form>

POST request:

$("#sub").click(function(){
    var sendf = {
        id: $("#id").val(),                             
        name: $("#name").val()
    };
    $.ajax({
        type: "POST",
        url: "",
        data: sendf,
        dataType: "text",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function(response, status, xhr) {                                                             

        },
    }); //ajax ends
    event.preventDefault();
    $(this).unbind();
});//sub click ends

Am I doing anything wrong? On button click, its just a simple POST request that takes place. Any help is appreciated. Thanks !

RPichioli
  • 3,245
  • 2
  • 25
  • 29
rnaikzz
  • 113
  • 2
  • 13
  • Possible duplicate of [HTML5 validation before ajax submit](http://stackoverflow.com/questions/15713491/html5-validation-before-ajax-submit) – Luke Oct 14 '16 at 22:52

2 Answers2

1

The problem is you are intercepting the click action on the button - so the html form validation never takes place and the POST will process happily because you never check that the form is valid before sending it.

It works fine the second time because after the first click you have unbound your click handler and the form submits using a regular form submit event - resulting in the page reloading as it is no longer being handled by the AJAX request (in the now unbound click handler).

If you instead bind your function to the form's submit event, the browser will run the HTML form validation first, before calling your event handler. If you remove the $(this).unbind(); you will continue to submit the form via AJAX and not with a page reload.

use this code (jsFiddle demo):

$("form").on("submit", function(ev){
    ev.preventDefault(); //prevent regular form submission via a page reload

    var sendf = {
      id: $("#id").val(),                             
      name: $("#name").val()
    };

    $.ajax({
           type: "POST",
           url: "https://httpbin.org/post",
           data: sendf,
           dataType: "text",
            headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function(response, status, xhr) {                                                             
                console.log(response);
            },

        }); //ajax ends
});//sub click ends

If you do want to disable submitting the form more than once, see this question.

Community
  • 1
  • 1
Luke
  • 418
  • 4
  • 11
  • The above code still resulted in a page reload. The validation and other stuff worked fine but I dont want the reload to happen. – rnaikzz Oct 14 '16 at 22:58
  • Not in the fiddle i provided, it doesn't. Are you sure you copied it correctly? `$("form").on("submit", function(ev){ ev.preventDefault();` is the part that stops regular submission of the form, check you are using the same variable in the function arguments and the preventDefault() line. Also check that your jQuery selector is correct - if you have more than one `
    ` element it might be binding to the wrong form.
    – Luke Oct 17 '16 at 15:37
  • The above code works. As you mentioned, there was another form element, so the binding was wrong. Thank you . – rnaikzz Oct 17 '16 at 17:26
0

Is there any javascript being executed on it? Because when I import this HTML into a codepen, the required works as expected...

Edit

The event.preventDefault(); is preventing the default behaviour of the "required".

Kevin
  • 1,219
  • 1
  • 16
  • 34
  • Except for the Ajax Post request on submit, nothing else is getting called on it. – rnaikzz Oct 14 '16 at 22:22
  • Perhaps you should just disable that at first, see if it has desired behaviour then. If it does, you can build up from there again where your problem might be... I would really be stumbled if that html still behaves like that when there's nothing else being called on it – Kevin Oct 14 '16 at 22:24
  • I will give that a try. Thank you :) – rnaikzz Oct 14 '16 at 22:26
  • Well it works fine without the POST request being attached to it. Any suggestions as to where I can look for the issue ? – rnaikzz Oct 14 '16 at 22:28
  • I added event.preventDefault(); as my modal window in which the form showed up would close and the whole page would refresh on submit of the form, which I didnt want to happen. – rnaikzz Oct 14 '16 at 22:47