0

I am trying to pass the ajax response obtained from view to the template using HttpResponse but I don't have any idea, how to do that?

view.py

 analyzer=SentimentIntensityAnalyzer()
    def index(request):
        return render(request, "gui/index.html")

    @csrf_exempt
    def output(request):
        sentences = request.POST.get('name',None)
        senti = analyzer.polarity_scores(sentences)
        context_dict = {'sentiment': senti}
        return render(request,"gui/index.html", context = context_dict

I want the senti to be printed after the score on the page but I am unable to obtain it.

template file

<!doctype html>
<html>
     <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
       </script>
     </head>
     <body>
       <form action = Post>
                    Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br>
         <input onclick = "testfunction()" type = "button" value = "Submit" >
        </form>
        <div><strong>Score is {{ sentiment }}</strong></div>
    </body>
    <script>
    var testfunction = () => {
    var test = document.getElementById("name").value
    console.log(test)

    $.ajax({
             type: "POST",
             dataType: "json",
             url: 'output/',
             data:{
                    csrfmiddlewaretoken: '{{ csrf_token }}',
                   'name': test
                    },
                    success: function(response) {
                    console.log("Succesful return firm ajax call");
                    },
                    error: function(result){
                    console.log("Failure");
                    }
             });

    }
    </script>
</html>

enter image description here

8
  • So, you want to show retrieved data from in a specific place right? Commented Oct 12, 2018 at 10:22
  • Yes , after the word score in template file Commented Oct 12, 2018 at 10:23
  • what is the intended use? I'm assuming the view shown corresponds to the URL of your Ajax call - and it responds with html (the rendered template). You can easily just dump this html into a particular container, in your success callback, Commented Oct 12, 2018 at 10:23
  • ah, thanks for the edit. In that case don't bother with the {{ sentiment }} template variable. Just put an empty div here and populate it with the response to the Ajax call. Commented Oct 12, 2018 at 10:24
  • 1
    Why have you asked this question again? As I told you last time, Ajax is completely pointless here and you should remove it. Commented Oct 12, 2018 at 10:30

1 Answer 1

1

In your view.py return render(request,"gui/index.html", context = context_dict code is missing ending paranthesis.


This is the correct order of jQuery ajax:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

Your success and error fields are inside of data.


<script>
    $(document).ready(function(){
        $("button").click(function(){
            $.ajax({url: "demo_test.txt", success: function(result){
                $("#div1").html(result);
            }});
        });
    });
    </script>
    </head>
    <body>

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

    <button>Get External Content</button>

    </body>

This is an example of how to use .html method of ajax jquery. You can adjust for your own.


Additionally, use below code to loop through response:

  $.each( data, function( key, val ) {
    HTMLString += <li id='" + key + "'>" + val + "</li>
  });

and this should be inside of the function of success and then pass HTMLString into .html method

To make it clearer how to $.each works:

var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
  console.log(index + ':' + value); 
});
Sign up to request clarification or add additional context in comments.

9 Comments

Can you post the output
Now ,its same as the screenshot ,i pasted above but without the values after score in preview method
Don't forget that you are getting a dictionary as a response. You need to loop through it
How did you use the suggested .html method? It shouldn't be the same even you don't loop.
Because your ajax doesn't return with success. Look at your image it is consoling error message 'Failure'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.