When Django encounters a request with the method "POST," it mistakenly interprets it as a "GET" request

I recently encountered a problem with an AJAX request that I haven't been able to resolve. Here's the code snippet in question:

    <script type="text/javascript">
$('#activeform').on('submit', function(event){
        event.preventDefault();
    var _self = $(this);
    var token = $('input[name="csrfmiddlewaretoken"]').val();
        alert( _self.serialize())  // sanity check
            $.ajax({
        type: _self.attr('method'),
        url: _self.attr('action'),
        data: _self.serialize(),
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        headers: {"X-CSRFToken": token},
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Accept-Charset","utf-8");
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");},
                success: function(json) {
                    alert("Send!")},
                error: function( xhr, textStatus ) {
                alert( [ xhr.status, textStatus ] )},
            complete: function() {
                    alert("Complete")},
            crossDomain: false
            });
return 
}); </script>

The AJAX request seems to work fine as I get success and complete messages, and my browser recognizes it as a POST request on submission. However, when checking for request.method == 'POST' in my Django view, it returns False. Any ideas on what might be causing this issue?

Answer №1

Implementing registration with ajax was a challenging journey for me. However, the code snippet below helped me achieve my goal.

<body>
<div class='large-3 large-offset-3 columns'>
    <form method='POST' id="activeform" >
    {% csrf_token %}
    {{form}}
    {% if error %}
    <p><h6>{{error}}</h6></p>
    {% endif %}
    <input type='button' class='button' value='Register' onclick="submit_by_id()"> 
    </form>
</div>


<script type="text/javascript">
    function submit_by_id()  {
        alert('Before Ajax');
        var token = $('input[name="csrfmiddlewaretoken"]').val();
                $.ajax({
            method: "POST",
            url: "/auth/registrate/",
            data: $('#activeform').serialize(),
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            dataType:"html",
                    success: function(data, textStatus, jqXHR) {
                        // Code in this block executes on successful message submission
                        alert("Success" + data + 'Serialized string ' + $('#activeform').serialize())},
                    error: function( xhr, textStatus ) {
                    alert( [ xhr.status, textStatus ] )},
                complete: function() {
                        // Code in this block executes on successful message submission
                        alert("Complete")},
            headers: {"X-CSRFToken": token, "HTTP_X_REQUESTED_WITH": "XMLHttpRequest"},
            crossDomain: false

        });
    }
</script>

</body>

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

Utilizing v-model dynamically to showcase the outcomes of a specific property within a v-for iteration

As I iterate over an array using v-for, the number of items in this array varies each time. Currently, I am able to input values into the fields and have them correctly update the data property associated with them. However, there are two issues that need ...

Tips for extracting a textfield input value and sending it using data-ajax-url="Url.Action() in a cshtml file

I have a challenge with my controller function that takes two dates as parameters. It works perfectly when I hardcode the dates, but I'm struggling to extract values from my text fields and pass them to the function. I prefer not to use a form in my c ...

Successive Alerts with Material-UI and React-Redux

After realizing that having multiple snackbars scattered across different components was messy, I decided to revamp my app by creating a single custom component that can be called using Redux to display any type of snackbar needed. Desired outcome: I exp ...

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

Chrome: When enlarging an image, the overflow of the outer div is disrupted

My image wrapper is designed to hide overflow when hovered over. It works well in Firefox and Opera, but Chrome displays it strangely. I've created a 10-second screen recording to demonstrate the issue. Watch it here: I also tested it on JSFiddle, ...

Having trouble with your Jquery resize or scroll function?

function adjustNavbar() { if ($(window).width() > 639) { $(document).scroll(function () { if ($(window).scrollTop() > 60) { $('.navbar').addClass('background', 250); } else { ...

Is it advisable to combine/minimize JS/CSS that have already been minimized? If the answer is yes, what is

Our app currently relies on multiple JS library dependencies that have already been minified. We are considering consolidating them into a single file to streamline the downloading process for the browser. After exploring options like Google Closure Compi ...

Using Express.js with Pug.js, dynamically render the page with new content following a fetch POST request

I have a collection of article previews sourced from a database and rendered on the webpage using a Pug.js mixin. each article in articles +articlePreview(article.title, article.text, article.imgSrc) To enhance the user experience, I want to implem ...

Improving performance in Next.JS by optimizing unused JavaScript resources

Currently working on my first website using Next.js and experiencing poor performance scores after running a lighthouse test. The issue seems to be related to unused JavaScript files located in the chunk folder. I've come across suggestions to split t ...

How can I retrieve the decimal x and y coordinates when the mouse is moved in Typescript Angular?

I am in the process of transitioning my user interface from Flash/Flex, where it stores values in decimal format. I need to access and reuse these values. Here is a demo showcasing my problem. Here is a snippet: import { Component, Input } from '@an ...

Retrieving location data using the Google Maps geocoder

Could someone help me with this issue in my code? function getLocationName(latitude, longitude) { if (isNaN(parseFloat(latitude)) || isNaN(parseFloat(longitude))) { return false; } var locationName; var geocoder = new google.maps. ...

Having difficulty accessing information from the parent scope

As I continue to dive into AngularJS, I've encountered some challenges with scopes in my current project. Here is my controller and directive setup: angular.module('myModule', []) .controller('myController', ['$scope', ...

Refresh KendoUI Grid data with latest additions

I currently possess: $.post('buying-grid/split/' + config.route.params.id, item).success(function(data){ var ds = new kendo.data.DataSource(); ds.data(data) $('#buyingGrid').data('ke ...

Conceal image and substitute with a different image using JavaScript

My query pertains to JavaScript: how can I create an effect where clicking the jump-down button opens a text box and causes the button to change direction and rotate? I am considering using two photos - one hides when the jump-down button is clicked, and ...

Change the x and y positions of several div elements as the mouse moves in JavaScript

I am aiming to create a webpage where multiple divs with text and other content move along the x and y axes of the mouse. The desired effect is similar to parallax scrolling, but I have found that existing parallax plugins are image-based and do not work w ...

Resetting JavaScript Input based on certain conditions

I have been attempting to reset the input fields for a login when the loginDiv display is set to none, but unfortunately it does not seem to be working as expected. My goal is for the input fields to reset whenever the login button is clicked and the logi ...

The useRoutes function is returning null despite the correct pathname being provided

Check out my React code snippet! I've got the Component nestled within a micro-frontend application, which is then brought into the main app using module federation. // embedded in my microfrontend. const path = '/another-component-path'; f ...

Poor initial placement of the Dialogs when the content exceeds the space available

While using material-ui^0.20 with react^16.2, I encountered an issue when initially displaying a Dialog containing a Component with excessive content. The problem is illustrated in this image: https://i.sstatic.net/RF8Mu.png This is the expected appeara ...

Is it possible to use wildcards in Socket.io rooms or namespaces?

The hierarchy I am working with is as follows: Store -> Manager -> Assistant In this setup, a Manager has access to everything that the Assistant sends, while the Assistant can only access what the Manager explicitly provides. My understanding is t ...

Should I retain a duplicate of the js library in the lib or vendor directory even if it has already been installed using npm?

Query 1 : As I install my project dependency libraries using npm, they are saved in the npm_modules folder. I wonder if it's necessary to also duplicate the library files like angular.js, angular-route.js in a separate lib or vendor folder for permane ...