I am trying to learn how to integrate ajax with django. When I click the button, the javascript function change() changes the content of the button to 'X' and then ajax is evaluated. But the control is not passed from the client to server side on button click as ajax neither returns success nor failure. It's been two days since I am stuck with ajax. Here is the full code:
url file:
from django.conf.urls import include, url
from django.contrib import admin
from game import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^handler/',views.index,name='index'),
url(r'^$',views.home,name='home'),
]
views file:
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def index(request):
print "xyx"
if request.method == 'POST':
return HttpResponse("sucess")
else:
return HttpResponse("failure")
@csrf_exempt
def home(request):
context = {}
return render(request,"game/home.html",context)
home.html file:
<head>
<head>
<script>
function change()
{
var y = document.getElementById("one");
y.value = 'X';
$.ajax({
url:"127.0.0.1:8000/handler/",
type:"POST",
data:{},
cache:false,
success:function(data) {
var x = document.getElementById(data);
x.value = 'O';
alert("sucess");
},
error:function(error) {
alert(error);
}
});
}
</script>
</head>
<body>
<input type = "button" id = "one" onclick="change()"></input>
</body>
</html>
Console output:
(django)shivam@shivam-HP-Pavilion-15-Notebook-PC:~/Python/django/django/django_test$ python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
December 05, 2015 - 18:48:10
Django version 1.9, using settings 'django_test.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Dec/2015 18:48:16] "GET / HTTP/1.1" 200 453