Reputation: 27038
i've been doing a lot of ajax scripts and every time something seems to be different.
in this case i have a form that i want to post
<form id="sss">
<input id="qqq"/>
<input type="submit" id="s" href="Search!"/>
</form>
<div id="rrr"></div>
and
$('#s').click(function(){
$.ajax({
url: 'foo.php',
data: {
query: $('#q').val()
},
success: function(data) {
$('#rrr').html(data);
}
});
return false;
});
and
if(isset($_REQUEST['query'])){
print_r($_REQUEST['query']);
}
what happens is that in <div id="rrr"></div>
gets loaded the print_r($_REQUEST['query']);
and all the rest of the html page.
i only want to return $_REQUEST['query']
weird!?
any ideas? What this success: function(data){}
actually means?
Thanks
Upvotes: 2
Views: 134
Reputation: 56769
If you are requesting the same page that you are current displaying, then your if
statement doesn't stop processing, so the rest of the page is returned as well. You either need to die()
afterward, or (recommended) create a separate page entirely dedicated to handling AJAX requests. Here's an example of how to properly stop processing:
if (isset($_REQUEST['query'])) {
print_r($_REQUEST['query']);
die(); // stop processing.
}
In regards to your second point, I think you might be misunderstanding the technical details of what's actually happening here:
foo.php
from server. Server executes foo.php
according to the logic in the page, and sends response output to browser. Browser renders the page.foo.php?query=...
foo.php?query=...
(just like it did in step (1)!), which causes the first if
to trigger before returning the rest of the html in response, so the same page is returned except with the query output at the top (Try going directly to foo.php?query=...
in your browser and I think you'll see what I mean).data
.function success(data)
is executed, passing the exact output returned from the server as-is from the AJAX request (i.e., the variable contains the same as viewing the source of foo.php?query=...
in your browser), which is then processed according to your logic. In this case, you are dumping the contents into a div
, so you see the output correctly.Please take a moment to install and run Fiddler, so you can see the exact data that is flowing back and forth as you load the page in your browser, and then watch what happens as you make an AJAX call. Perhaps it will make the data flow and results you are getting much clearer.
Hope this helps!
Upvotes: 2