Java script request via Ajax is failing to execute

Within my HTML code, I have included a button like so:

<button type="submit" id="post-form" class="btn btn-primary" onclick="send()">Send</button>

Accompanying this is the JavaScript function send() :

function send() {
           
            $.ajax({
                type: 'POST',
                url: "http://app.localhost/feedback",
                dataType: "json",
                data : {
                    feedback: $('#feedback').val(),
                    email: $('#email').val(),
                },
                success : function(json) {
                    $('Backdrop').hide();
                    console.log("requested access complete");
                }
            });
        }

In my Django project views, there is a function associated with the /feedback entry point. However, the process stalls before reaching the success stage. Interestingly, while I can send requests using Postman, executing them through JavaScript proves futile.

The view pertaining to the designated entry point appears as follows:

@csrf_exempt
def feedback(request):
    if request.method == 'POST':
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        fromField = body['email']
        subject = 'New FeedBack from {}'.format(fromField)
        body = body['feedback']
        sendEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1d4c9f1d4c99fd2de">[email protected]</a>", subject, body,
                  replyTo=['<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0c5d8e0c5d88ec3cf">[email protected]</a>', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395c41175c41795e54585055175a5654">[email protected]</a>'])

    return redirect('/')

Answer №1

Is the button in question meant for submitting a form? If so, there's no need for an onclick event on the button. You can achieve the desired functionality with the code snippet below:

<form id="yourForm">
  <button type="submit" id="post-form" class="btn btn-primary">Send</button>
</form>

$("#yourForm" ).submit(function() {
  $.ajax({
    type: 'POST',
    url: "http://app.localhost/feedback",
    dataType: "json",
    data : {
        feedback: $('#feedback').val(),
        email: $('#email').val(),
    },
    success : function(json) {
        $('Backdrop').hide();
        console.log("requested access complete");
    }
  });
});

I hope this solution proves helpful to you.

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

Populate a form with data retrieved from a MySQL query result

One aspect of my project involves a specific interface called 'designation.php' that contains a form. The goal is for users to enter a 'designation code' (which serves as the primary key) and then click the 'update' button, pr ...

What is the best way to layer div elements using Bootstrap 4?

I'm looking to achieve a similar effect with overlapping elements as shown in the attached file. What would be the best code approach to achieve this? I am currently using bootstrap 4.6.2, can it be of assistance? Thank you for your guidance. Althou ...

Using NodeJS to facilitate communication between multiple NodeJS instances while also overseeing operations of a Minecraft server

I have a question about communicating between NodeJS instances. Let's say I have one NodeJS instance running a chat room - how can I access that chat and see who is connected from another NodeJS instance? Additionally, I'm curious if it's f ...

Ensuring that a minimum of one checkbox has been selected

When employees submit a work order, they fill out a form that includes a section titled "Departments Affected" with checkboxes for 5 different departments. The form is set up so that at least one department must be checked before it can be sent. I have imp ...

Using Jquery to toggle classes between "display block" and "display none

Hello friends, I'm in need of some help with my code. $(document).ready(function() { var circle = $('.circle'); $(".send a").click(function(e) { e.preventDefault(); $('.wrap').css('display', 'bl ...

Can beautifulsoup handle scraping a "dynamic webpage"?

I am exploring the use of beautifulsoup for web scraping, despite my lack of theoretical knowledge about webpages. I believe I have grasped the basics and will try my best to articulate my question. By a dynamic webpage, I mean a site that changes its HTM ...

Attempting to dynamically update the image source from an array when a click event occurs in a React component

Has anyone successfully implemented a function in react.js to change the image source based on the direction of an arrow click? For instance, I have an array set up where clicking the right arrow should move to the next image and clicking the left arrow s ...

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

Loading React.js components before data fetch is complete

My app is encountering an issue where it renders before the fetch operation is completed, resulting in incorrect rendering. Below is the code snippet: componentWillMount() { fetch('http://localhost:8081/milltime/login?users='+this.state.e ...

Strange results appearing on my node.js server - removing object

When I run node.js in the terminal, I get this output: node server.js { hand: [ [ [Object], [Object] ], [ [Object], [Object] ], [ [Object], [Object] ], [ [Object], [Object] ] ], deck: [ { suit: 'c', rank: 'a' ...

Utilizing GUID model binding within ASP.NET MVC

Can someone please assist me in resolving this issue? I've been struggling to find the solution and it seems like there's something obvious that I'm missing... The problem I am facing involves sending a GET request from my JavaScript code, ...

Checkbox in Bootstrap with an elongated label

This specific CSS code is used to style checkboxes. It scales the size, adds margin, and a border to create a distinctive appearance. input[type='checkbox'] { transform: scale( 2 ); margin-right: 1.5em; border: 1.5px solid black; } W ...

Load Vue dynamically to implement reCAPTCHA script

I am looking for a way to dynamically load a script like recaptcha specifically within the Register.Vue / login.Vue component. <script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer> </s ...

Changing the background color completely

Need help with CSS! I have two divs, one with a background color of #000 and the other with a transparent PNG image as the background. I want to override the background color with transparency from the PNG file so that the background doesn't cover th ...

Angular JS: Distribute objects from a single array to various arrays or services

I have recently embarked on developing a basic app using Angular JS, utilizing a service/factory to manage data and enable the addition of objects. Within the array of various individuals (listed in the html), you can include them as candidates by employi ...

Implementing a Responsive Form on an Image Using Bootstrap

I am facing a challenge where I need to position a form on top of a Responsive Image. My goal is to ensure that the form is responsive as well and adjusts its size according to the image. As of now, the image is responsive but I am struggling to make the ...

Issues with expected identifiers and type mismatch errors encountered when defining a TypeScript class

As someone who is still relatively new to coding, I am facing a challenge while trying to create a TypeScript class within an Angular project that is based on a complex JSON file. The issue arises from the way the properties were defined in the JSON using ...

The pusher mistakenly sends duplicate messages with just a single submission

I am experiencing a strange issue where Pusher is sending the message twice upon submission, even though I cannot find any function being repeated or called two times in my code. For this project, I am using React version 18.1.0 and Golang version 1.18 im ...

Utilize the power of RxJS to send numerous post requests within an Angular application

I have a form where users input names and count numbers. My goal is to append the number to each name. For example, If a user enters "worker" and a count of 5, I want to add numbers from 1 to 5: worker-1, worker-2, worker-3, worker-4, worker-5. After cr ...