Mansa
Mansa

Reputation: 2325

AJAX form only allows one submission?

I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?

How do i accomplish the form and script so I do not have to refresh?

Here is the form:

<form role="form" class="form-horizontal validate" name="create_form" id="create_form">

<div class="form-group">
    <label class="col-sm-2 control-label" for="name">Name</label>

    <div class="col-sm-10">
        <input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
    </div>
</div>

<div class="form-group-separator"></div>

<div class="form-group">
    <button id="submit_btn" class="btn btn-success">Create</button>
    <button type="reset" class="btn btn-white">Reset</button>
</div>

</form>

And here is the AJAX part:

$(document).ready(function(){

    $("#submit_btn").on("click", function () {

        $.ajax({
            type: 'POST',
            url: 'data/create.php',
            cache: false,
            data: $('#create_form').serialize() 
        })
        .done(function(data){ 
            $("#name").val("");
        })
        .fail(function() { 

            console.log("ERROR");

        });

        // Prevent refreshing the whole page page
        return false;

    });
});

Hoping for help and thanks in advance :-)

Upvotes: 0

Views: 59

Answers (2)

Syed Moiz
Syed Moiz

Reputation: 38

use submit instead of click.

$('#submit_btn').on('submit', function(e) {
    e.preventDefault();
    ... //rest of the code
});

Upvotes: 2

NIV
NIV

Reputation: 486

I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.

<button onclick="myFunction()">Click me</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}
</script>

Upvotes: 0

Related Questions