Nick Dill Nick Dill - 3 months ago 32
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.

$.ajax({
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();
request.open('POST', '/platform/post-tracking/', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);


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 = 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

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);
request.send(data);