I was expecting the below scenario common, but couldn't find much help online. I have a form loaded through Ajax (say, create entity form). It is loaded through a button click (load) event
$("#bt-create").click(function(){
$ ('#pid').load('/controller/vehicleModel/create3');
return false;
});
the response (a form) is written in to the pid element. The name and id of the form is ajax-form, and the submit event is attached to an ajax post request
$(function() {
$("#ajax-form").submit(fun开发者_Python百科ction(){
// do something...
var url = "/app/controller/save"
$.post(url, $(this).serialize(), function(data) {
alert( data ) ; /// alert data from server
});
I could make the above ajax operations individually. That is the ajax post operation succeeds if it calls from a static html file. But if I chain the requests (after completing the first), so that it calls from the output form generated by the first request, nothing happens. I could see the post method is called through firebug. Is there a better way to handle above flow?
One more interesting thing I noticed. As you could see, I use grails as my platform. If I keep the javascripts in the main.gsp (master layout), the submit event would not register as the breakpoint is not hit in firebug. But, if I define the javascript in the template file (which renders the form above), the breakpoint is hit, but as I explained, the action is not called at the controller. I changes the javascript to the head section but same result.
any help greatly appreciated. thanks, Babu.
You need to register the form submit handler in the success handler of the first ajax request:
$("#bt-create").click(function() {
$('#pid').load('/controller/vehicleModel/create3', function() {
$("#ajax-form").submit(function() {
// do something...
var url = "/app/controller/save"
$.post(url, $(this).serialize(), function(data) {
alert( data ) ; /// alert data from server
});
});
return false;
});
Also I would recommend you using the jQuery form plugin. Your code will look like this:
$('#bt-create').click(function() {
$('#pid').load('/controller/vehicleModel/create3', function() {
$('#ajax-form').ajaxForm(function() {
alert('thanks for submitting');
});
});
return false;
});
No need fetch form url, serialize parameters, etc...
the jQuery form plugin helped me to shorten the code, and seems to have more options (calllbacks) for finer control. But, the code suggested by Darin worked great as well. For anyone reading this post, to answer the second part of my question. the $(document).ready() only fires after the document initially loads. If you want to bind events DOM elements that are generated or included after, you may bind the event using .live (ver 1.3+). see the documentation at http://api.jquery.com/live/ thanks.
精彩评论