I have a model object from twitter bootstrap which is as follows
<!-- Name Edit div -->
<div id="form-content" class="modal hide fade in" tabindex="-1">
<form name="form" action="<c:url value="/editname" />" method="post">
<div class="modal-header">
<h4>Edit Name</h4>
</div>
<div class="modal-body">
<div class="control-group">
<div class="controls">
<ul class="nav nav-list">
<li class="nav-header">First Name</li>
<li><input type="text" placeholder="First Name" name="firstName" id="firstName" class="input-xlarge help-inline"></li>
<li class="nav-header">Last Name</li>
<li><input type="text" placeholder="Last Name" name="lastName" id="lastName" class="input-xlarge help-inline"></li>
</ul>
</div>
</div>
</div>
<div class="modal-footer">
<button id="submit" class="btn btn-success">Update</button>
<button class="btn" data-dismiss="modal" >Close</button>
</div>
</form>
</div>
and my ajax script is like follows:
$(function() {
//twitter bootstrap script
$("button#submit").click(function(){
var $form = $(this).closest("form").attr('id');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(msg){
$("#thanks").html(msg);
$("#form-content").modal('hide');
},
error: function(){
//alert("failure");
}
});
});
});
But the request is not firing. I checked in firebug and it looks like it's not able to get the form object and the request is not going to the controller. How can i make it work. I will have multiple forms in the same page in future.
I would suggest you use the .submit() function:
$(function() {
$('#form_id').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(msg){
$("#thanks").html(msg);
$("#form-content").modal('hide');
},
error: function(){
//alert("failure");
}
});
});
});
Set the form id to something and change the javascript to match
You can also add a data-ajax="true"to all the forms you want to submit bia ajax and then use:
var forms = $('form[data-ajax="true"]');
forms.submit(function(e){
e.preventDefault();
// do ajax
});
<form name="form" action="<c:url value="/editname" />" method="post">
One thing is that you did not given a id for form.
var $form = $(this).closest("form").attr('id');
And if the id exist(if u adding it through code), then above $form will contain the id of the form. That is a string.
So use like this,
var $form = $(this).closest("form");
instead
var $form = $(this).closest("form").attr('id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With