i am using a table with different rows and an edit button on each row.
This edit button creates a form using ajax / json to fill the form details depending on the row clicked.
The problem then comes when creating the ajax for this form.
Im using the same method as always, but for some reason the ajax submission is not working on this form and its just going to the process PHP page.
Im just wondering if this is because the form is not on the page when the javascript code for the ajax call is loaded?
So an example:
1) The page is loaded and included on that page is:
<script type="text/javascript" src="admin/js/showUserDetailsForm.js"></script>
<script type="text/javascript" src="admin/js/saveUserDetails.js"></script>
2) I click edit, and the showUserDetailsForm.js creates the form. The form is this:
$('<div id="admin-edituser-popup">'+
'<div id="login-popup-title">Edit User:<button id="closeedituserform">Close</button></div>'+
'<div id="login-popup-centre">'+
'<form class="editUserDetails-form" action="admin/process/saveUserDetails.php" method="POST">'+
'Editing Details for User:'+response.username+' , User ID:'+response.userID+
'<input type="hidden" name="userid" value="'+response.userID+'">'+
'<input type="text" name="username" value="'+response.username+'">'+
'<input type="submit" value="Save User">'+
'</form>'+
'</div>'+
'</div>').appendTo('body');
3) I click the submit button, and its correctly returns the JSON i am looking for (updateSuccess).
4) The form is not processed via ajax, its simply going to where its action is.
The code for the ajax call on save details is:
// JavaScript - Save user details
$(document).ready(function(){
// When the form is submitted
$(".editUserDetails-form").submit(function(){
$.ajax({
type: "POST",
url: "admin/process/saveUserDetails.php",
data: $(".editUserDetails-form").serialize(),
dataType: "json",
success: function(response){
if (response.updateSuccess) {
alert('Saved');
}
}
});
return false;
});
});
I cannot see any reasons why that its not working (cant find any errors with class names etc) and there is not errors in the javascript.
The only thing i am unsure of is the fact that the form is created AFTER the code is loaded?
Thanks!
For newly created DOM element handlers, you should use JQuery's on()
.
For your issue, you should just replace $(".editUserDetails-form").submit(function(){
with $("body").on('submit', '.editUserDetails-form', function(){
Last but not least, @Brunis is right - you should add event.preventDefault() to your method (event parameter is automagically injected)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments