How can I pass the ajax response obtained from the view
to the template
using HttpResponse
? I'm unsure of the process.
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'd like the sentiment to be displayed after the score on the page, but I'm having trouble achieving this.
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>