Imagine the following index.php :
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="MY_FORM" action="./index.php" method="get">
<input name="var_name">
<input type="submit">
</form>
<!-- <div> -->
<div id="MY_CONTENT">
<?php
var_dump( $_GET );
?>
</div>
<!-- </div> -->
<script type="text/javascript">
$('#MY_FORM').submit(function()
{
var form = $(this);
$.get('./', form.serialize(), function(data)
{
var updated = $('#MY_CONTENT', data);
$('#MY_CONTENT').replaceWith(updated);
});
return false;
});
</script>
</body>
</html>
There is a simple AJAX form. When this form is submited then MY_CONTENT should be refreshed with AJAX (hence form's action="./index.php"). Question: I found the code working only when MY_CONTENT div is enclosed in the another div.
I placed the
<!-- <div> -->
<!-- </div> -->
around MY_CONTENT. this must be changed to div to get the script working.
Why does MY_CONTENT have to be wrapped in a div?
This happens because data
contains all elements that were children of the head and body tags, but not the head/body itself. you can get rid of the wrapper by using
var updated = $(data).filter("#MY_CONTENT")
instead since it is a direct child of the body tag after you get rid of the wrapper.
Another solution (as pointed out by Fabrício Matté) is to only return the target html if the request is an ajax request.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && Strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
var_dump( $_GET );
}
else {
... rest of your page ...
then you can just do
$('#MY_CONTENT').html(data);
replace
var updated = $('#MY_CONTENT', data);
$('#MY_CONTENT').replaceWith(updated);
by:
$('#MY_CONTENT').html(data);