Reputation: 1957
I'm using jQuery's form plugin to submit a form asynchronously. The server sends back HTML which goes into a div #boardcontainer by setting the target of an ajaxForm call. This works fine.
...
var options = {
target: '#boardcontainer', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#myForm').ajaxForm(options);
...
Problem is, the HTML that comes back from the server contains two divs:
<div id="board">
...
</div>
<div id="status">
...
</div>
"#board" is a giant HTML table prerendered by the server. "#status" is a short message and should ideally go into a div other than #boardcontainer.
What's the best way to handle this situation? Can jquery change a div's parent? If so I can change the parent in the post-submit callback, but I can't seem to find a way to do it.
Upvotes: 0
Views: 2866
Reputation: 1957
I ended up building the divs with json (with the html for the divs embeded as strings, though)
Here's the code:
$(document).ready(function () {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
dataType: 'json'
};
$('#myForm').ajaxForm(options);
});
function showResponse(data) {
$('#statusTarget').html(data.status);
$('#boardcontainer').html(data.board);
};
It works and both the #statusTarget and the #boardTarget are replaced with the new html every time the form is submitted.
Upvotes: 0
Reputation: 532465
In your success callback you could rearrange the divs using appendTo. Alternatively you could return json and build the divs in your success callback.
$('#status').appendTo('#realTarget');
EDIT: Upon checking, appendTo itself does what you need it to do without losing the event handlers.
Upvotes: 3