check if form is submitted successfully html5

28,666

Solution 1

You should use the form's onsubmit event. It sounds like you are listening on the submit button's click event which isn't right.

The form's submit event will only fire if the form is valid. The HTML5 validation rules will prevent this event from firing if the form is invalid.

jsFiddle demo

$('#myform').submit(function(e){
    e.preventDefault();

    // do ajax now
    console.log("submitted"); 
});

Solution 2

try this function:

    $("input[type='submit']").click(function () {
    var form = $(this).parents("form:first");
    form.submit(function () {
        //  validate submitted successfully according to html validation
        //  ajax here
    });
});

Solution 3

Based on your comment, I think this is what you are looking for-

on 'onsubmit' attribute of 'form' call a function. In that function, do the validation, and then make an ajax call if the fields are valid, otherwise don't.

Share:
28,666
Junaid Atique
Author by

Junaid Atique

I am a PHP developer. PHP is my love. I love to explore different prospects of PHP.

Updated on July 13, 2022

Comments

  • Junaid Atique
    Junaid Atique almost 2 years

    I have following code.

    <div class="form-group">
        <label for="store_account_name">Store Title</label>
        <input type="text" value="" class="form-control" name="store_account_name" id="store_account_name" placeholder="Please insert store title of the external store" required />
    </div>
    <div class="form-group">
        <label for="store_url">Store URL</label>
        <input type="url" value="" class="form-control" name="store_url" id="store_url" placeholder="Please insert store URL as described in help section" required />
    </div>
    

    On submit button I want to check if form is validated. I have an listner event which has preventDefault button. So I want to send ajax call only when both of these inputs are successfully validated. Is there any JS function to check the status of validation or any css property is add to invalid field.

  • Junaid Atique
    Junaid Atique about 10 years
    It will do the ajax even if the fields are not validated.
  • MrCode
    MrCode about 10 years
    Not true at all. It will not fire if the form is invalid. See fiddle in answer.
  • Junaid Atique
    Junaid Atique about 10 years
    Thanks your answer was correct. The problem is I have included a js file that create problem. That js file require the form to have data-validate="true" attribute and when it is placed it overrides its functionality.
  • FreeLightman
    FreeLightman over 7 years
    It does not answer the question 'check if form is submitted successfully html5'. Your examples only shows how to make an ajax call and prevent default form submitting. Maybe the answer resolves the problem of those who asked, but nothing more. The question is open. Remove required attributes from jsfiddle example, and your code would not work.