RobinReborn
RobinReborn

Reputation: 451

Why do I get a 500 internal service error when doing an AJAX post in Django

I am trying to send data to my database without having to load a new page. Here is my Javascript:

    function submit(){
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/185post/", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("noun=bananas&userAnswer=textajaxNow");
}

That will be processed by the following function in views.py:

def _185post(request):
    joke =Joke185.objects.all().filter(noun=request.POST.dict()['noun'])
    _185Joke = Joke(text=request.POST.dict()['userAnswer'],source='improv')
    _185Joke.save()
    print (_185Joke)
    joke[0].joke.add(_185Joke)
    joke[0].answers += 1
    print (joke[0].answers)
    joke[0].save()
    print (joke[0].save())

As you can see there are several print statements there and they all return what I expect them to, so I'm not sure why I'm getting a 500 Internal Service Error

Upvotes: 0

Views: 68

Answers (1)

Mohammad Efazati
Mohammad Efazati

Reputation: 4910

If you return something, your issue will solve, but there are more code suggestion

1- Don't use _ for starting functions

2- use logger instead of print

from django.http import JsonResponse

def _185post(request):
    joke =Joke185.objects.all().filter(noun=request.POST.dict()['noun'])
    _185Joke = Joke(text=request.POST.dict()['userAnswer'],source='improv')
    _185Joke.save()
    print (_185Joke)
    joke[0].joke.add(_185Joke)
    joke[0].answers += 1
    print (joke[0].answers)
    joke[0].save()
    print (joke[0].save())
    return JsonResponse(joke[0])

Upvotes: 1

Related Questions