4

I am trying to implement file upload using ajax with Django but facing some problem.

When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.

{"status": "error", "result": "Something went wrong.Try Again !!"}

Django Version: 1.6.2

Python Version: 2.7.5

Also, testing on Django Development Server.

views.py

def upload(request):
        logging.info('Inside upload view')
        response_data = {}
        if request.is_ajax():
                logging.info('Is_AJAX() returned True')
                form = UploaderForm(request.POST, request.FILES)

                if form.is_valid():
                        logging.info('Uploaded Data Validated')
                        upload = Upload( upload=request.FILES['upload'] )
                        upload.name = request.FILES['upload'].name
                        upload.save()
                        logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)

                        response_data['status'] = "success"
                        response_data['result'] = "Your file has been uploaded !!"
                        response_data['fileLink'] = "/%s" % upload.upload

                        return HttpResponse(json.dumps(response_data), content_type="application/json")

        response_data['status'] = "error"
        response_data['result'] = "Something went wrong.Try Again !!"

        return HttpResponse(json.dumps(response_data), content_type='application/json')

Template

<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
                {% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>

Javascript 1:

$('#uploadForm').submit(function(){

        var formData = new FormData($(this)[0]);
        $.ajax({
                url: '/upload/',
                type: 'POST',
                data: formData,
                async: false,
                success: function (data) {
                alert(data)
                },
                cache: false,
                contentType: false,
                processData: false
        });
        return false;
});

Javascript 2

var options = {
      url: '/upload/',
      type: "POST",
       error: function(response) {
               alert('Something went Wrong. Try Again');
        },
        success: function(response) {
            if ( response.status == 'success' ) {
              alert('success');
             }
        }
};

$('#uploadForm').ajaxSubmit(options);

Question:

1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.

2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?

There is another similar question here but with no result.

Community
  • 1
  • 1
g4ur4v
  • 3,210
  • 5
  • 32
  • 57
  • Are you using a plugin for sending the file through ajax? because if not, that might be the problem. – yuvi Apr 19 '14 at 08:33
  • Also - can you check the headers of the request being sent and share the details? – yuvi Apr 19 '14 at 08:36

3 Answers3

4

This works for me. You need a jquery.form.js

$("#uploadForm").submit(function(event) {
    $(this).ajaxSubmit({
        url:'{% url upload_file %}',
        type: 'post',
        success: function(data) {
            console.log(data)
        },
        error: function(jqXHR, exception) {
            console.log("An error occurred while uploading your file!");
        }
    });
    return false;
});

Here's the similar question here with answers.

Community
  • 1
  • 1
Ralph
  • 430
  • 2
  • 9
  • Hi, I don't know why it still doesn't work for me. in javascript 2 in the question , I am using `jquery.form.js`.I tried your code but still getting the same problem. – g4ur4v Apr 22 '14 at 08:22
2

Make sure that javascript code block

$('#uploadForm').submit(function(){

    var formData = new FormData($(this)[0]);
    $.ajax({
            url: '/upload/',
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
            alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
    });
    return false;
});

loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.

apopovych
  • 175
  • 1
  • 7
-1

1) why is_ajax() not working? Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.

Take a look at http://jquery.malsup.com/form/

If it's already done, you might take a look at the HTTPRequest object

Django Documentation says HttpRequest.is_ajax() Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.

2) Why page redirects?

As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()

 $('#uploadForm').submit( function (){
     $(this).ajaxSubmit(options);
 return false;
 });

Hope this was helpful :)

jayraj
  • 31
  • 5