skip to Main Content

I am trying this below requirement where there is a voice synthesizer and it converts my voice (which is a question) into a text and it sends that text to the back-end Django through Ajax.

At the back-end, Django takes that data and use that data (question) to access the database and get the result and send that result to the frontend which should get caught by the success part of the Ajax. But it’s not working.

I am not able to figure out where is the problem. I am posting the Ajax and Django code below for your reference.

views.py

def GetAnswer(request):
    if request.method=='GET' and request.is_ajax():
        question_asked=str(request.GET.get("message_now"))
        try:
            answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0]
            print(answer)
            data={"data":answer}

            return JsonResponse({"success": True}, data, status=200)
        except:

            return JsonResponse({"success": False}, status=400)
    else:
        print("Not Suceess")

main.js

function chatbotvoice(message) {
  const speech = new SpeechSynthesisUtterance();

  if (message !== null && message !== '') {
    $.ajax({
      url: "http://127.0.0.1:8000/getanswer",
      type: 'GET',
      data: {
        message_now: message
      },
      success: function (data) {
        speech.text = JSON.parse(data);
        window.speechSynthesis.speak(speech);
        chatareamain.appendChild(showchatbotmsg(speech.text));
      },
      error: function (error) {

        speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours";
        window.speechSynthesis.speak(speech);
        chatareamain.appendChild(showchatbotmsg(speech.text));
      },
    });
  }
}

I tried to check whether the Ajax request is reaching the function and I am able to view the value of the variable "question_asked" in the back-end.

2

Answers


  1. return JsonResponse({"success": True}, data, status=200)
    

    that line will fail with some error message, because you pass data as a second positional argument. Django documentation tells you that second positional argument is encoder. Since a list with data isn’t an encoder – you will get an error.

    Your error would be catched by try/except block. So the execution flow will move to except block – where you return {"success": false} JSON response.

    So your code should become like this:

    def GetAnswer(request):
        if request.method=='GET' and request.is_ajax():
            question_asked=str(request.GET.get("message_now"))
            try:
                answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0]
                print(answer)
                data={"data":answer}
    
                return JsonResponse({"success": True, "data": data}, status=200)
            except:
    
                return JsonResponse({"success": False}, status=400)
        else:
            print("Not Suceess")
    

    Please, refer to this part of documentation for more details https://docs.djangoproject.com/en/3.1/ref/request-response/#jsonresponse-objects


    UPDATE (21.09.2020)

    You should fix this line:

    answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0]
    

    to

    answer=QuestionAnswer.objects.filter(question=question_asked).values_list('answer', flat=True)[0]
    

    because there’s no value_list function, but there’s values_list.

    UPDATE 2 (21.09.2020)

    So the final code should be:

    def GetAnswer(request):
        if request.method == 'GET' and request.is_ajax():
            question_asked = request.GET["message_now"]
            try:
                answer = QuestionAnswer.objects.filter(question=question_asked).values_list('answer', flat=True)[0]
                return JsonResponse({"success": True, "answer": answer}, status=200)
            except:
                return JsonResponse({"success": False}, status=400)
    

    and JS code should be modified as well

    function chatbotvoice(message) {
      const speech = new SpeechSynthesisUtterance();
    
      if (message !== null && message !== '') {
        $.ajax({
          url: "http://127.0.0.1:8000/getanswer",
          type: 'GET',
          data: {
            message_now: message
          },
          success: function (data) {
            if (data.success == true){
              speech.text = data.answer;
              window.speechSynthesis.speak(speech);
              chatareamain.appendChild(showchatbotmsg(speech.text));
            } else {
              speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours";
              window.speechSynthesis.speak(speech);
              chatareamain.appendChild(showchatbotmsg(speech.text));
            }
          },
          error: function (error) {
            speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours";
            window.speechSynthesis.speak(speech);
            chatareamain.appendChild(showchatbotmsg(speech.text));
          },
        });
      }
    }
    
    Login or Signup to reply.
  2. $.ajax({
      crossDomain: true,
      url: "{% url 'getanswer' %}",
      type: 'GET',
      data: {
        message_now: message,
        'csrfmiddlewaretoken': '{{ csrf_token }}'
      },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search