AJAX Upload using django-ajax

debug in chrome

Django-ajax is one module I’ve come to love on my present project and I see myself using it a lot in the future. It takes care of the nitty gritty and lets me focus on the important stuff.

I’ve been shoving requests and responses back and forth these past 1 week, and everything was dandy…until this morning.

I had the need to upload a csv file using ajax (ajax because there was further action needed on the part of the user), and I felt it was going to take me just 20mins to figure out…first, the Django side…then the JS portion.

It has taken me 3hours (being awake) and 2hours (being asleep). I will say this was due to me being stubborn (I should have just passed the options via ajaxSetup)…and that feeling we have when we rely on “greater work”, that it just has to work.

I still cannot tell if it’s Chrome, JQuery, or the module, but it was impossible to pass options to ajaxPost. Below, I show you what doesn’t work, and what worked.

$("form").submit(function(e){
    e.preventDefault();
    var data = new FormData($(this)[0]);

    ajaxPost(url, data, function(content){
        console.log(content.result);
    },{processData:false,contentType:false,cache:false});

Even with the options (the last parameter to ajaxPost) passed, it still data didn’t submit and raised Uncaught TypeError: Illegal invocation
You need to add this snippet just before the above…and delete the options

$.ajaxSetup({
    crossDomain : false,
    processData: false,
    contentType: false,
    cache: false
});

Hopefully, someone else will figure why $.ajax would not accept anything besides the ‘on’…(e.g onError, onSuccess) options.

Update!

There’s nothing like good sleep and breaks inbetween sprints when one programs. I actually made an error with my statement that options wasn’t working correctly. Frankly, I’m not a pro javascript programmer, but I should have observed from the above that I was passing “variables”, not keys in <code>{processData:false,contentType:false,cache:false}</code> It should rather read

{"processData":false,"contentType":false,"cache":false}

I ran into an issue where the ajaxSetup defined for one form applied across the entire page (including other forms). It turns out that according to https://api.jquery.com/jquery.ajaxsetup/ , ajaxSetup “is not recommended”, because

The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

So, you see…just pass options in.

Worked for me after wondering for a whole day what was going on.