Nick Dill Nick Dill - 2 months ago 11
Javascript Question

How to send an Ajax post to a Django form without JQuery

I'm currently sending posts with ajax to a django form, but I need to do this without JQuery.

Here's the working JQuery version.

url : "/platform/post-tracking/",
type : "POST",
async: true,
data : {
account : 229829623,
width : pageWidth

How would I send this post request without JQuery?
I've tried this

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

But the form isn't valid.

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 =

session = TrackedSession()
session.account = temp.account
session.trackedIp = trackingip
session.width = temp.width
print("Session Created")
print "Form isn't valid."
print form.errors
response_data = "Success"
return HttpResponse(


The data argument to request.send() needs to be a URL-encoded string. jQuery converts an object to a string, but if you don't use jQuery you have to do it yourself.

data = 'account=229829623&width=' + encodeURIComponent(pageWidth);