Reputation: 98
I have a form that I'd like to have the data submit however not refresh the page. I've added this code which stops the refresh but has also stopped the submit. Is there a way to do this when using preventDefault()?
$("editUserForm").on('submit', function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: 'POST',
data: $("editUserForm").serialize()
})
});
Upvotes: 1
Views: 656
Reputation: 1773
Here is code to submit form using ajax without refresh page.
<form name="addstudent" id="addstudent" action="add.php" method="post">
<fieldset><legend>Add student to tutoring list</legend>
<div><label for="studentid">ID number</label><input type="text" name="studentid" id="studentid"></div>
<div><label for="assignment">Tutoring assignment</label><select name="assignment" id="assignment">
<option value="">Please select an assignment</option>
<option value="att">Activity Time</option>
<option value="acc">ACC</option>
<option value="tech">ACC Tech </option>
<option value="ast">After School</option>
</select></div>
<div><label for="teacher">Assigning teacher</label><input type="text" name="teacher" id="teacher"></div>
<input type="submit" name="submit" value="submit" id="submit">
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").on('submit',"#addstudent" ,function (e) {
e.preventDefault();
$.ajax({
url: $( '#addstudent' ).attr( 'action' ),
type: 'POST',
data: $("#addstudent").serialize(),
success: function(data) {
console.log(data);
}
});
});
});
</script>
Upvotes: 0
Reputation: 25820
Your selector will only select elements of the type editUserForm
, as in:
<editUserForm></editUserForm>
You probably meant to select the form either by its id:
$("#editUserForm")
<form id="editUserForm"></form>
$("form[name='editUserForm']")
<form name="editUserForm"></form>
Upvotes: 1