1

Can someone help me submit a form using AJAX? The purpose of the form is to upload a file. The specific problem I'm having is how to capture the action and enctype parameters. My form:

<form role="form" method="post" action="http://localhost:3000/api/some_url" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input id="submit" type="submit" class="btn btn-primary" value="Submit">
</form>

I need something like:

$.ajax({

  type: "POST",
  url: 'http://localhost:3000/api/some_url',
  action: 'http://localhost:3000/api/some_url',
  enctype: 'multipart/form-data',
  headers: {
          'x-access-token': this.token,
  },
  success: function () {

    console.log('success!')
  },
  error: function (a, b, c) {
    console.log(a)
    console.log(b)
    console.log(c)
  }
})

Can someone help?

Thanks in advance!

1
  • 1
    For file upload try dropzone.js, which is easy and awsome Commented Oct 20, 2016 at 22:31

1 Answer 1

2

Give id to your form

<form id="frm_upload_image" role="form" method="post" action="http://localhost:3000/api/some_url" enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <input id="submit" type="submit" class="btn btn-primary" value="Submit">
</form>

after that make following changes in your ajax call

var form = new FormData($("#frm_upload_image"));
   $.ajax({
        url: $("#frm_upload_image").attr('action'),
        type: "POST",                
        data: form,
        contentType: false,       
        cache: false,             
        processData:false,                                  
        success:function() {    
            console.log('success!')
        },
        error: function (a, b, c) {
            console.log(a)
            console.log(b)
            console.log(c)
        }
      });
});

it works for me

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.