I’m a jQuery noob here, please help! Much much appreciated!
my urls.py:
url('^xhr_test/$','posts.views.xhr_test'),
my views.py:
def xhr_test(request):
if request.is_ajax():
message = "Hello AJAX"
else:
message = "Hello"
return HttpResponse(message)
So, very simple. This setup works if one of two versions of my HTML page.
HTML version 1 is a success:
<script type="text/javascript">
$(document).ready(function() {
$.get("xhr_test", function(data) {
alert(data);
});
});
</script>
That’s that. The AJAX request is made whenever the page is done loading. So that much works, and I get a nice alert box that says “Hello AJAX”
Now HTML version 2 does not work:
$(document).ready(function() {
$("a").click(function() {
alert("hi");
$.get("xhr_test", function(data) {
alert(data);
});
});
});
<a href="">Click here</a>
So when I click “Click here” I get an alert with “hi” in it, and then nothing. Nothing seems to be sent nor received, because I don’t see anything in Firebug. I also tried changing the request URL from “xhr_test” to “myApp/xhr_test” and “/myApp/xhr_test” to no avail.
What am I doing wrong?
Thank you very much!
Try adding an
event.preventDefault();to your code; e.g.: