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"
)