Search code examples
javascriptphpajaxform-submitpreventdefault

Javascript form submit preventDefault not working when form is retrieved with AJAX


I have a form, which I submit with Javascript and preventDefault. Everything works fine. However, when I retrieve the form with an AJAX call together with other data from a DB, the form will not submit with Javascript anymore, but tries to refresh the entire page with the normal action="" and method="post". It seems that due to the AJAX call, the preventDefault is somehow disabled?

AJAX Call to get form and other data from DB:

<a href="#" onClick="return false" onmousedown="javascript:loadnames('<?php echo $postid;?>');">Load Names</a>

<div id="form-container"></div>
<!-- is empty, but contains the form upon ajax call above-->

The AJAX retrieved HTML Form to submit with Javascript:

<div id="form-container">
<!--let user add a name to DB not contained in DB list below-->
<form method="post" action="" id="addnameform">
<input name="name" id="name" type="text" value=""/>
<input type="submit" name="add-name-submit" value="Add"/>
</form>
<!--get a list of names from DB-->
<?php
$sql = "SELECT * FROM names ORDER BY name ASC";
$query = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($query)) { 
$name = $row["name"];
echo ...
} // end while
?>
</div><!--end-container-->

Javascript to submit HTML form above:

$("#addnameform").submit(function(event) {
event.preventDefault();
var $form = $("#addnameform");
var name = $form.find( "input[name='name']" ).val();
$.ajax({
url: "ajax.php",
type: "POST",
... 

As said, everything works perfectly when the form is displayed on the page upon page load. But as soon as I wrap it inside a container, which at first is "empty", but shows up upon an AJAX call, the preventDefault is somehow disabled.


Solution

  • You have to bind the submit event to your body (or any other parent DOM which exists from begining)

    $("body").on('submit', '#addnameform', function(event) {
        //...
    });