Reputation: 1366
1. I'm trying to add ajax to my django web application... The code i've written is given below... for testing i wanted to display a text in the html element whose id="id_ajax1"... the code successfully displays the text, but it automatically reloads the page again...
2. when I write the 1st one from the code given below this line, the behaviour is as mentioned above... when I write the 2nd one from the code below, it shows broken pipe ('127.0.0.1', 46958)
return HttpResponse("text to be returned asynchronously")
return HttpResponse("text to be returned asynchronously", mimetype="application/javascript")
The code:
ajax.html
<form action onsubmit="ajax1()">
<span id="id_ajax1"></span>
<button class="col-5" type="submit">click</button>
</form>
ajax.js
function ajax1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("id_ajax1").innerHTML = this.responseText;
}
};
var url = "test/ajax1";
xhttp.open("GET", "/test/ajax1", true);
xhttp.send();
}
urls.py
urlpatterns = [
url(r'^test/ajax1/$', views.ajax1, name='ajax1'),
]
views.py
def ajax1(request):
return HttpResponse("You have successfully written your first ajax code")
Upvotes: 0
Views: 133
Reputation: 161
There are multiple issues that could be causing this behavior:
ajax1()
function should return false
to prevent the browser from automaticly sending the form.xhr.open()
is not the same as the url defined in urls.py
application/javascript
is used for sending actual Javascript code to the browser. The mimetype that you need for sending text (like with AJAX) is text/plain
. In your case there is no need for defining the mimetype at all.Upvotes: 1