Implementing robust security measures with Django 1.10 and AJAX, eliminating the need for HTML forms

When making a POST request via AJAX without an HTML form, do security issues arise? Why does no csrf error occur even though no csrf data is being sent and csrf is enabled in Django?

toggle-status.js

jQuery(document).ready(function($) {
    $("#switch-status").click(function(){
    $.ajax({
        url: '/account/switches/',
        data: {'toggle': 'status'}
    });
    });
});

view.py

@login_required
def switches(request):
    toggle = request.GET.get('toggle', None)
    current_user = request.user
    update = Switches.objects.get(owner=current_user)
    if toggle == 'status':
    if update.status is True:
        update.status = False
    else:
        update.status = True
    update.save()
    return HttpResponse('')

Answer №1

By default, the ajax function uses a GET method, not POST. Therefore, if you write:

$.ajax({
    url: '/account/switches/',
    data: {'toggle': 'status'}
});

You are actually making a GET request, not a POST request.

If you want to make a POST request, you should do it like this:

$.ajax({
    method: 'POST',
    url: '/account/switches/',
    data: {'toggle': 'status'}
});

Make sure to include the CSRF token, as attempting to POST without one will result in failure. Refer here for instructions on how to do so.

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

Using JQuery to parse data in a $.post request

My goal is to dynamically populate textboxes using JQuery based on an array sent from an external PHP file through json_encode(array). The chosen option in a select box determines which value is sent to the PHP file. Despite my efforts to debug using tools ...

Even if objects are deleted from a table in Django, they can still persist when accessing the model

I am currently developing a Django application that utilizes a PostgreSQL backend. As part of this development, I am working on a separate Python script to make modifications to the database table (which is represented as a model in Django) and then genera ...

Django Template needs to display 'description' instead of the actual content

When working with a Model containing a CharField and choices specified, such as: class MyModel(models.Model): THE_CHOICES=( ('val',_(u'Value Description')), ) ... myfield=models.CharField(max_length=3,choices=TH ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

Exploring the Power of JSON-Objects in AJAX

I need help loading only a portion of a text file (*.txt) into my HTML. The other part of the file provides information about the number of li's in it. The content of the text file is structured as a JSON-Object and here is an example: {"content": [ ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Getting rid of unwanted scrollbars in a breeze

I am facing an issue with two nested divs that have the same height settings. The outer div has a max-width/height constraint along with overflow auto, causing scrollbars to appear when the inner content exceeds its dimensions. However, even if I resize ...

Handling Ajax errors in jQuery with MVC 3

I'm currently working on a code snippet that involves opening a dialog with a specific View. $('.bulkEditlink').click(function () { var f = $('td:first', $(this).parents('tr')).text(); var r = tableCols().toStrin ...

What is the best way to execute a function in JavaScript and have it return the output as an image

I have created a special function that selects the image source based on a given criterion: function facilityImg(arr, x) { switch (arr[x]) { case 'Yes': return "Images/checked.png"; case 'No': ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...

Uncaught ReferenceError: ajaxUrl is undefined

After pressing a green button on the website , instead of the expected popup image and email confirmation, I receive an error message stating "ajaxUrl is not defined". I have attempted to find a solution to this problem by searching on Google and Stackove ...

Generating dynamic form fields in Django

I am looking to create a form with a 'rooms' field, which will be an integer field. Based on the number of rooms entered, I would like to generate two additional fields for each room: 'extra_adult' and 'extra_children'. Furthe ...

The tab directive does not function properly on an input field that is created using ng-repeat

I am currently working on developing a web app using Ionic and AngularJS, and I have encountered a problem. I created a directive to make the keyboard act as "Tab" when pressing "Enter" for input fields. It works perfectly fine with static tags in HTML. Ho ...

Advantages of choosing between the <NextLink/> and the <Button href="/somePage"/> components in the powerful Mui React UI libraries

Currently engaged in a project, I am wondering if there exists a substantial disparity in the utilization of these two components. Prior to this change, the return button was implemented as follows: <NextLink href="/settings" ...

What is the best way to initiate animation on a child element once the parent element has reached 75% completion of its animation

Is there a way to use JavaScript to determine when an animation is 75% complete? I have many nested HTML elements that need to be animated with an animation delay property, where the nested animation should start when the parent element is 75% complete. I ...

What is the best way to link individual items in a dynamic list with a unique ui-sref attribute?

I have a pagination system that retrieves items from a JSON file. The items can be added or removed. I want to create a link for each item that leads to a configuration view (each item should have its own unique configuration). I am seeking the best way to ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

How to insert commas in a string at specific positions using JavaScript

At this moment, my simple numpad is set up to input a dollar amount into the span tag .bill-amount__integer. The initial text in this span is 0.00. <div class="bill-amount__value"> <span>$</span><span class="bill-amount__integer"& ...

Using jQuery checkboxes with ajax for data submission and storage in PHP without the need for insertion

Seeking guidance on how to properly serialize elements value instead of pushing it, as I am encountering an issue where each value is being inserted into the database 9 times. Any assistance in figuring out this problem would be highly appreciated. The HT ...

Accessing variable from JavaScript function in Python App Engine

Embarking on my first journey into the world of web technologies, I find myself tangled in a dilemma. Currently immersed in my initial appengine project, I am attempting to manipulate a value generated within a JS function (embedded in my .html file) using ...