php - Javascript form submit preventDefault not working when form is retrieved with AJAX -
i have form, submit javascript , preventdefault. works fine. however, when retrieve form ajax call other data db, form not submit javascript anymore, tries refresh entire page normal action="" , method="post". seems due ajax call, preventdefault somehow disabled?
ajax call form , other data db:
<a href="#" onclick="return false" onmousedown="javascript:loadnames('<?php echo $postid;?>');">load names</a> <div id="form-container"></div> <!-- empty, contains form upon ajax call above-->
the ajax retrieved html form submit javascript:
<div id="form-container"> <!--let user add name 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 list of names db--> <?php $sql = "select * names order name asc"; $query = mysqli_query($connection, $sql); while ($row = mysqli_fetch_array($query)) { $name = $row["name"]; echo ... } // end while ?> </div><!--end-container-->
javascript 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, works when form displayed on page upon page load. wrap inside container, @ first "empty", shows upon ajax call, preventdefault somehow disabled.
you have bind submit event body (or other parent dom exists begining)
$("body").on('submit', '#addnameform', function(event) { //... });
Comments
Post a Comment