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
If you are requesting the same page that you are current displaying, then your
ifstatement doesn’t stop processing, so the rest of the page is returned as well. You either need todie()afterward, or (recommended) create a separate page entirely dedicated to handling AJAX requests. Here’s an example of how to properly stop processing:In regards to your second point, I think you might be misunderstanding the technical details of what’s actually happening here:
foo.phpfrom server. Server executesfoo.phpaccording 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 firstifto 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 tofoo.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 offoo.php?query=...in your browser), which is then processed according to your logic. In this case, you are dumping the contents into adiv, 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!