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>

https://i.sstatic.net/dofFi.png

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

Transferring files with Node.js via UDP connections

I'm currently working on setting up a basic Node.js server that is designed to receive files from clients through UDP. The challenge I'm facing is that whenever I attempt to send a large file (anything over 100kb), the server appears unresponsive ...

Animating jQuery Accordion in Horizontal Direction Extending to the Far Right

After implementing a horizontal accordion in jQuery based on the tutorial found at the following link: A minor issue arose during animation where a slight space was added on the far right side, causing the tabs to shift slightly. This problem is particula ...

"Successful JSON response in Django when accessed through a web browser, but encountering issues in both Postman and

I'm encountering an issue with sending a JSON response from my Django back-end to the Angular front-end. Strangely, when I make the request, I receive nothing in Postman or Angular. However, if I open the link directly in a browser, it seems to return ...

What is the best way to ensure that the checkbox is not affected when you click on the area?

If the user interacts with the checkbox, I don't want the handleClick function to execute. Is there a way to exclude it or prevent the click event from triggering? <div ... onClick={this.handleClick}> <div> some content here < ...

Struggling to verify credentials on CouchDB

I'm currently facing an issue with authentication while trying to access a couch server from a web application served on port 80. The credentials seem to be removed when passing them in the URL and the session cookie isn't sent to the server. He ...

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Error Message: REST Framework returns a 404 status code when attempting to

I created an endpoint with @api_view in my Django project, but for some reason the rest_framework does not seem to be registering it properly. As a result, whenever I try to send a request to api/main-filter/, I receive a 404 error. Why is this happening? ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Unable to choose anything within a draggable modal window

Can someone please assist me? I am struggling to figure this out. I can't select text inside the modal or click on the input to type text into it. I suspect it may be due to z-index issues, but I'm having trouble locating them. var currentZ = n ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

I am experiencing an issue with the checkbox in my React app where the state is not updating after it has been

I am currently building a todo app using React, but I'm encountering an issue where nothing happens when I click the checkbox. I've provided my code below: App.js import './App.css'; import React from 'react' import TodoItem ...

Express Power Tool - Error: app.set function is undefined

My journey with creating an API using Node/Express began with a solo endeavor to learn the basics in a 'naive' manner. The initial setup worked smoothly, prompting me to experiment with express-generator. Upon completion of the setup process, th ...

Bind a function to the final element of each piece of changing content

I'm facing a challenge in associating a function with every nth element, just once for each element. The concept is to trigger an ajax call when the final element comes into view. I am utilizing a useful jquery plugin called inview. My list consists ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...

Implementing jQuery to trigger actions on every other click

Here we have a snippet of code that either posts and updates #arrival or removes it and replaces it with standard text. One click for posting, another click to reset. The issue is that currently it requires two clicks to do the initial posting, followed by ...

Press `Enter` to confirm your selection in the BootstrapVue message box input box

Using Vue version v2.6.12 BootstrapVue version v2.21.2 Is there a way to confirm by pressing Enter instead of manually clicking OK? let text this.$bvModal.msgBoxConfirm(<input vModel={text} />) https://i.sstatic.net/7XxOl.png ...

Emails sent through an HTML form submission should always include a valid "from"

I am currently in the process of creating a feedback form that allows individuals to provide anonymous feedback. I have explored nodemailer and node-sendmail, but I have encountered an issue with both requiring a from address. While I am aware that this ca ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

Instantiate a child class within an abstract class by utilizing the keyword "this"

Within my code, there is an abstract class that uses new this(). Surprisingly, this action is not creating an instance of the abstract class itself but is generating an instance of the class that inherits from it. Even though this behavior is acceptable i ...