AJAX post request with django and python

Tags: , , , ,



I am trying to build a web app on django where a user can record something which then gets turned into text and after that sent to the server with AJAX. I did some research and found this article: https://medium.com/@manask322/implementing-speech-to-text-feature-in-a-django-app-f0fa53bb3e03

So I copied the html code: (this is only the part I copied)

<div id='result'>
    Your text will  appear here
  </div>
  <br>
  <div id= 'record'>
      <button onclick="startConverting()" class='btn btn-info btn-sm' id="re">record</button>
      <button class='btn btn-info btn-sm ml-3' value="Send" id="send">Send</button>
  </div>

  <script>
     function startConverting()
            {
              document.getElementById("re").style.visibility = "hidden";   
              var r=document.getElementById('result');
              var spr=new webkitSpeechRecognition(); //Initialisation of web Kit
                spr.continuous=false; //True if continous conversion is needed, false to stop transalation when paused 
                spr.interimResults=true;
                spr.lang='en-IN'; // Set Input language
                spr.start(); //Start Recording the voice 
                var ftr='';
                spr.onresult=function(event){
                    var interimTranscripts='';
                    for(var i=event.resultIndex;i<event.results.length;i++)
                    {
                        var transcript=event.results[i][0].transcript;
                        transcript.replace("n","<br>")
                        if(event.results[i].isFinal){
                            ftr+=transcript;
                        }
                        else
                        interimTranscripts+=transcript;
                    }
                    r.innerHTML=ftr +interimTranscripts ;
                };
                spr.onerror=function(event){};
            }
            $(document).ready(function() {
                $("#send").click(function(event){
                      $.ajax({
                          type:"POST",
                          url:"/audio_data",
                          data: {
                                  send : $('#result').html()
                                  },
                          
                      });
                });
              });
  </script>
</div>

But changed the function in views.py a bit:

@csrf_exempt
def audio_data(request):
    if request.method == 'POST':
        result = request.POST['send']
        return render(request, 'success.html')
        
        
    elif request.method == 'GET':
        return render(request, 'afterContinue.html')

The recording works and it also displays the text you say but when you click on send nothing happens. Does someone know why?

UPDATE: This is the urls.py part:

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

Answer

You can try this:

Add the jQuery CDN minified inside the <head> tag in html template:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    </head>
    <body>
       <div id="result">
            .......
       </div>
    </body>
</html>

Html template

  1. send a parameter save to audio_data view so that it could recognise that it has to save the audio text.
  2. send the ajax request data in json format.
  3. Check the response sent by django view was true or not.
  4. redirect the user to /audio_data?success=true if the response from view was true.
$(document).ready(function() {
    $("#send").click(function(event){
        $.ajax({
            url:  "/audio_data",
            data: {
               'save': true, // Change No.1
               'text': $('#result').html()
            },
            dataType: 'JSON', // Change No.2
            success: function(response) {  // Change No.3
                if (response.ans) {  // Change No.3
                   location.href = '/audio_data?success=true'; // Change No.4
                }
            }
        });
    });
});

views.py

  1. Check if the save parameter is true or not.
  2. Check if audio text is provided or not.
  3. Return a JsonResponse with a dictionary that holds the value of ans variable that is True if the audio text is saved & is False if the text is nor provided.
  4. Render the success.html template if the success parameter is true.
  5. If both save and success parameters are False or not provided then render afterContinue.html template.
from django.http import JsonResponse

@csrf_exempt
def audio_data(request):
    data = request.GET

    if data.get('save', False): # Change No.5
       ans = True

       text = data.get('text', False) # Change No.6
       if text: // Change No.6
          print('Text = ', text)
          """ Here save the text the way you want. """
       else:
          ans = False

       return JsonResponse({'ans':ans}) # Change No.7

    elif data.get('success', False): # Change No.8
       return render(request, 'success.html')

    return render(request, 'afterContinue.html') # Change No.9


Source: stackoverflow