Incorporate an Ajax response script with a Django HttpResponse

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>

Answer №1

The code in your view.py file is missing an ending parenthesis. Make sure to add it to the render function:

return render(request, "gui/index.html", context=context_dict)
.


Here is the correct order of using jQuery ajax:

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

Note that the success and error fields should be inside the data object.


<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 example demonstrates how to use the .html method with Ajax in jQuery. Customize it as needed for your own purposes.


Furthermore, here's a code snippet to loop through a response using $.each:

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

Make sure this is within the success function, and then pass the HTMLString variable to the .html method.

To better understand how $.each works, consider this example:

var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
  console.log(index + ':' + value); 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

pressing the switch will adjust the size of the container

I am looking to implement a feature where clicking on an icon will resize a div to full screen in the browser. Below is the HTML code I have set up for this functionality, and I am open to suggestions on how to achieve this. <div> <a (click)= ...

Executing a Rails Ajax request to communicate with a different controller

I'm new to using Ajax and feeling a bit disoriented. My goal is to call the index method of the company_pays controller from a view managed by the companies controller. I want to replace the div company_content with the data returned from the AJAX req ...

The Server Components render encountered a glitch

Screenshot of the errorI am encountering a strange error only in the production environment. The lack of additional information leads me to believe it may be due to security measures put in place for production. Unfortunately, I have been unable to repli ...

Create dynamic animated QR codes using Swedish BankID with Python and hmac encryption

I'm currently working on a Django project that involves integrating BankID for authorization and digital signing. I found the pybankid library to be quite helpful in this process, but now I've hit a roadblock while trying to utilize the code prov ...

Delete the parent div when the button is clicked

trying to create a dynamic button system to add/remove inputs on clicks. I have the addButton working but not the deleteButton. What am I missing? $(document).ready(function() { var maxFields = 20; var addButton = $('#plusOne'); va ...

My attempt at utilizing the regex function was unsuccessful

When attempting to use a regex function for matching tags in the title and caption, it appears to work fine. However, adding more matching tags causes the function to fail. Below is the code snippet that functions correctly without any issues: $(".si ...

Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you ha ...

Transform the JSON structure with the power of JavaScript

Seeking assistance in converting the following array of JSON using either javascript or jquery: [ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":4 ...

Guide on how to streamline JSON output from aggregation result

I have written a NodeJs api using mongo db aggregation to obtain some output. However, the result I received is not what I expected. Can anyone help me figure out how to get the desired output? app.get('/polute', function (req, res) { Light. ...

The onbeforeunload event should not be triggered when the page is refreshed using a clicked button

Incorporated into my webpage is a sign-up form. I would like it to function in a way that if the user accidentally refreshes, closes the tab, or shuts down the browser after entering information, a specific message will appear. <input type="text" place ...

Using Handlebars JS to incorporate HTML tags such as <li>, <br>, and more in your data

Is there a way to use handlebars to display a list of data in an unordered format, with "title" and "articles" as the main categories? The issue arises when some of the articles contain HTML tags, such as <a> for links. In my current code, instead of ...

Django Form isn't getting saved in the Database

Despite my diligent search through the site for a solution, I have come across many related questions but found no direct response. Out of my 3 apps in projects, 2 are functioning smoothly, while one particular app is not writing to the database. The othe ...

Spin the AngularJS icon in a complete 360-degree clockwise rotation

Hey there! I'm new to Angular and I'm trying to create a button that will make an icon inside rotate 360 degrees when clicked. Right now, the entire button is rotating instead of just the element inside it. I want only the "blue square" to rotate ...

Filtering in JavaScript can be efficiently done by checking for multiple values and only including them if they are not

In my current coding challenge, I am attempting to create a filter that considers multiple values and only acts on them if they are not empty. Take the following example: jobsTracked = [ { "company": "Company1", ...

AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service (function () { 'use strict'; angular .module('app.user') .factory('myService', Service); Service.$inject = ['$http', 'API_ENDPOINT', '$q']; /* @ngInject ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

Guidelines for choosing and uploading a file using Ionic

Is there a way to upload a PDF file to a server using the $cordovaFileTransfer plugin? I currently have an input field like this: <input type="file" onchange="angular.element(this).scope().fileNameChanged(this)"> How can I retrieve the pathForFile ...

Exploring touch interactions using D3.js and TUIO

I'm currently facing a challenge with implementing multi-touch functionality and the d3.slider in my D3 Map. You can see the current state of my project in this video. With the d3 slider, I can spawn points and navigate around the map using touch even ...

Check the output of the ChildProcess after executing a shell command

I am currently running the ChildProcess function within a Nextjs API route and I am struggling to retrieve the value from it. const output = exec( "curl -s -v https://test.com/index.php", (err, stdout, stderr) => { if (err) { ...

Issue with setInterval function execution within an Angular for loop

My goal is to dynamically invoke an API at specific intervals. However, when attempting to utilize the following code snippet in Angular 7, I encountered issues with the interval timing. I am seeking a solution for achieving dynamic short polling. ngOnIn ...