0

I'm experimenting a little bit with Django and Ajax. I want to make a simple view with a button that when someone clicks on it, the website alerts the data taken from another view in my views.py, which is an HttpResponse that says "foo". Currently, when I click on the button, nothing appears. I was wondering what has gone wrong here. My code is as follows:

In my views.py:

from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse

# Create your views here.
def index(request): 
    return render(request,"ajax/index.html")

def test(request): 
    return HttpResponse("foo")

In my index.html:

<body> 
<div> hello world </div> 
<button class="btn"> click this </button>
</body>
<script> 

$(".btn").click(function(){
    $.ajax({
        url: '//http://127.0.0.1:8000/test/',
        type: 'GET', 
        success: function(data) {
            alert(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("something went wrong")
        }
    }); 
});

</script>

In my urls.py:

from django.contrib import admin
from django.urls import path
from ajax import views as ajax_views 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',ajax_views.index,name="index),
    path('test/',ajax_views.test,name="test")  
]

Thank you for your time!

  • What if you use a `JsonResponse` (and pass an object) – Willem Van Onsem Aug 12 '20 at 22:48
  • It still doesn't work. I changed `return HttpResponse("foo")` to `return JsonResponse({"foo":"bar"})`, but nothing appears when I clicked on the button. Thank you for the suggestion though! – Đỗ Nguyên Tùng Aug 12 '20 at 22:53
  • @DoNguyenTung: perhaps you should take a look at the browser console, and see if it logs a warning/error when you fire the AJAX call (Ctrl+Shift+K in FF). Furthermore take a look to the server log to see if it receives a GET request. – Willem Van Onsem Aug 12 '20 at 22:57
  • @WillemVanOnsem Thank you for the suggestion. Currently, when I go to `http://127.0.0.1:8000/index/`, the browser (Chrome) console displays an error: `Uncaught ReferenceError: $ is not defined at (index):6`. Meanwhile, the server log only has `[12/Aug/2020 23:02:52] "GET /index/ HTTP/1.1" 200 406`. So I suppose there is a problem with how the Ajax is written? – Đỗ Nguyên Tùng Aug 12 '20 at 23:03
  • Update: Follow the advice of this SO thread https://stackoverflow.com/questions/22268881/referenceerror-is-not-defined. I add `` before the script in which I use ajax. Good thing is that the GET request is sent; however, it alerts "Something went wrong", which means the request is not successfully processed. – Đỗ Nguyên Tùng Aug 12 '20 at 23:07
  • Update #2: I get the Ajax working by fixing the URL from `url: '//http://127.0.0.1:8000/test/'` to `url: 'http://127.0.0.1:8000/test/'` . Thank you @WillemVanOnsem for helping me out with this! – Đỗ Nguyên Tùng Aug 12 '20 at 23:11

0 Answers0