Search code examples
ajaxdjangopython-2.7xmlhttprequest

AJAX gets access to Django HttpResponse variables


I am writing a small test app for a bigger project. I would like to use asynchronously FileReader() to read a txt file from client side and pass the textbody to the Django server by using AJAX. When the server succeeds to get the "posted" text, it will return the length of the text. It worked well on the server and I got what I expected. But now I would like to pass the size of the text(length) back to the client and display it somewhere on the web page asynchronously. But failed... Here is my code:

HTML

<script type="text/javascript">
    var render_text = function(csvFile, onLoadCallback){
        var reader = new FileReader();
        reader.onload = onLoadCallback;
        reader.readAsText(csvFile);
    }

    $(document).ready(function(){

        $("#id_csvFileInput").on("change", function(e){
            render_text(this.files[0], function(e){
                var text = e.target.result;
                $.ajax({
                    url: "",
                    type: 'POST',
                    async: true,
                    data: {'text': text},
                    success: function(data){
                        $("#id_test").text(data.size);
                    }
                });
            });
        });
    });

</script>

<p>
    <input type="file" name="csvFileInput" id="id_csvFileInput" accept=".csv">
</p>

<div>
    <p>Waiting for reponse context....</p>
    <span id="id_test">?</span>
</div>

View.py

# Home page.
@csrf_exempt
def home(request):
    template = 'hbvapp/home.html'
    context = {}
    if request.method == "POST" and request.is_ajax():
        context['test'] = request.POST.get('text')
        context['size'] = len(context['test'])
        print context['size']
        return render(request, template, context)
    else:
        return render(request, template)

ANY HELP WILL BE DEEPLY APPRECIATED ! Reagards


Solution

  • try it

    from django.http import JsonResponse
    
        if request.method == "POST" and request.is_ajax():
            context['test'] = request.POST.get('text')
            context['size'] = len(context['test'])
            print context['size']
            return JsonResponse(context)
            #       ^^^^^
    

    more details jsonresponse