Submitting an Ajax request to a Django form without relying on JQuery

I am currently using ajax to send posts to a django form, but I am looking to achieve this without relying on JQuery.

Below is the working code using JQuery.

$.ajax({
    url : "/platform/post-tracking/",
    type : "POST",
    async: true,
    data : {
        account : 229829623,
        width : pageWidth
    }
});

Is there a way to achieve the same post request functionality without using JQuery? I have attempted the following method:

data = {
        account : 229829623,
        width : pageWidth
}
var request = new XMLHttpRequest();
request.open('POST', '/platform/post-tracking/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

However, the form does not validate properly.

Django Form:

class TrackingForm(forms.ModelForm):
    class Meta:
        model = TrackedSession
        fields = ('account', 'width')

Django Model:

class TrackedSession(models.Model):
    account = models.IntegerField(default=0)
    width = models.IntegerField(default=0)

Django View:

def TrackDataView(request):
    if request.method == 'POST':
        form = TrackingForm(request.POST)
        if form.is_valid():
            print "Form is valid."
            temp = form.save(commit=False)

            session = TrackedSession()
            session.account = temp.account
            session.trackedIp = trackingip
            session.width = temp.width
            session.save()
            print("Session Created")
    else:
        print "Form isn't valid."
        print form.errors
    response_data = "Success"
    return HttpResponse(
        json.dumps(response_data),
        content_type="application/json"
        )

Answer №1

Ensure that the data parameter passed to the request.send() method is URL-encoded. When using jQuery, the object will be automatically converted to a string. However, if you are not using jQuery, you must perform this conversion manually.

data = 'username=123456789&height=' + encodeURIComponent(windowHeight);
request.send(data);

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

Concerns regarding the efficiency of JavaScript (Odin Project, Etch-a-Sketch) are arising

Currently, I am delving into Javascript on the Odin Project, tackling the Etch-a-Sketch exercise. This involves creating a board where you can draw with your cursor. As part of the exercise, there's a requirement to add a resize button that allows use ...

Utilizing Django sessions within testing environments

Hey there! I'm having trouble understanding how sessions work in Django. I run a shop where an anonymous user's shopping cart is linked to a session_key. The session key is retrieved from the request object. def _check_session(self, request) ...

Transform the array into a series of values separated by pipes

How can I transform an array like this - ["lat","long","abc","def","abcc","deef",] into [lat,long | abc,def | abcc,deef] using javascript? I am currently encountering an issue with the distance matrix API... Here is the code snippet I have: export asyn ...

Data not shown in original file display

I have just begun experimenting with Sencha's ExtJS. When we view the source file, it only shows the written code and does not display any applied styles or scripts that were added later in the "View Source." The same goes for AJAX; when we load cont ...

Modify CSS image according to the user interface language in asp.net

Is there a way to dynamically change the image based on different cultures in my ASP.NET webpage? I have successfully been able to switch strings using a resource file, but I am unsure how to handle images. Currently, I have an A tag with a specific clas ...

Unable to modify the .Text attribute of the asp:TextBox within the asp:UpdatePanel

I am facing an issue with updating values in dropdownlists and textboxes within an <asp:UpdatePanel> when editing details after selecting an item from an <asp:GridView>. It's important to note that the grid is not contained within the upda ...

Ensure that scripts with the type of "module" are completed before proceeding to execute the following script

In my HTML document, I have two script tags with type="module" at the bottom of the body tag. Following those, there is another script tag with embedded code that relies on the results of the first two scripts. Is there a method to ensure that this code ...

What is the best way to access a component's value from a different component in Vue script?

I have two Vue components in my PHP file: "application" and "vn" component. I am trying to fetch {{obj.vacancies_left}} from the "vn" component and use it in the "application" component. However, I keep getting an undefined variable error. I attempted to r ...

Guide to implementing endless ajax scroll pagination using Codeiginiter

I am attempting to implement infinite ajax scroll pagination on my blog, but unfortunately I am encountering an issue. The error message "server not responding..." keeps appearing despite troubleshooting efforts. Below is the code snippet being utilized: ...

There seems to be a problem with how the navbar is being displayed in ResponsiveSlides.js

I am currently using WordPress, but I have come here seeking help with a jQuery/CSS issue. I am utilizing responsiveSlides.js to create a simple slideshow, however, when viewing it here at gallery link, it appears that something is not quite right. STEPS: ...

Unusual occurrence while creating a unique identifier for a React component

I am working on creating a unique identification number for each React component, which will be assigned to the component upon mounting. Here is the approach I am taking: The callOnce function is used to ensure that a specific function is only executed on ...

Utilizing a promise array in conjunction with v-data-table

In my custom table component, I am using a v-data-table to display data that is passed as a prop. I perform some data cleaning operations and then call an asynchronous function to fetch additional data from an API: //load cloud storage data const cleanData ...

Fetch external data using AJAX

I am utilizing ajax to load external content by navigating through a menu. Everything is functioning properly. Users cannot reload the same content by clicking the menu tab repeatedly. However, first-time users can reload the content (first menu tab). I ...

While iterating over the key with a variable in a loop, only one property is displayed consistently instead of four different

Currently, I am working on creating an address book using JavaScript. The problem I am facing is that the properties of my objects are not providing me with the necessary information. I need 4 different properties instead of 4 loops with the same property. ...

Deciphering JavaScript Object

I'm currently using dropzone.js for ajax file uploads and I need a fallback solution for older browsers that do not support XMLHttpRequest. To address this issue, I've integrated the jQuery Iframe Transport plugin. $.ajax({ url: "/File ...

What is the process of converting the string 'dd/mm/yy hh:MM:ss' into a Date format using javascript?

I successfully completed this task. var date = 'dd/mm/yy hh:MM:ss'; var dateArray = date.split(" "); var splitDate = dateArray[0].split("/"); var splitTime = dateArray[1].split(":"); var day = splitDate[0]; var month = sp ...

The glTF file lacks visible content

My goal is to showcase a glTF file using Three.js. To bypass CORS policy, I have opted for a local server called Servez. While everything runs smoothly on Mozilla Firefox without errors, the content does not appear. However, when attempting the same on Chr ...

Vuejs is throwing an uncaught promise error due to a SyntaxError because it encountered an unexpected "<" token at the beginning of a JSON object

I am currently attempting to generate a treemap visualization utilizing data sourced from a .json file. My approach involves employing d3 and Vue to assist in the implementation process. However, upon attempting to import my data via the d3.json() method ...

Unable to locate _app.js file in nextJs

Currently, I am utilizing npx create-next-app for generating my NextJs project and now I am looking to incorporate global styles using bootstrap Upon downloading bootstrap, the suggestion was to add global styles in pages/_app.js, but I couldn't loca ...

Express Js: Implementing Dynamic Data Loading on Scroll

We are currently facing an issue where the dynamic data from Mongo db is loading all at once instead of through scrolling. Our objective is to have the data load progressively as we scroll, all on one single page. // We attempted using Lazy loading carous ...