0

I need to make a post call to a url with parameters lets say a="x", b="y", c="z" and d which is form data field. It is the file that i upload in the html form. On making an ajax call, i call.

 $.ajax({
         contentType: false,
         processData: false
         type: 'post',
         url:"some url i put here",
         data: {
             a: "x",
             b: "y",
             c: "z",
          }
  })
  .done(function(data){
      alert("Data: ", data);
  });

HTML part is

<body>
<input id="filey" type="file" size="40"><br><br>
<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

Note that a,b,c are known to me beforehand. How do i pass d?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Kanika Midha
  • 317
  • 1
  • 2
  • 9

1 Answers1

0

I realized that you were asking for Ajax file upload, and not just sending form data. This should work for you:

var files;

$('input[type=file]').on('change', function(event) {
  files = event.target.files;
});

$('form').on('submit', function(event) {
    event.stopPropagation();
    event.preventDefault();

    // Notify the user that this may take a while...

    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
             contentType: false,
             processData: false
             type: 'POST',
             url:"some url i put here",
             data: data,
             cache: false,
             dataType: 'json',
             success: function(data, textStatus, jqXHR) {
                 if(typeof data.error === 'undefined') {
                     submitForm(event, data);
                 } else {
                    console.log('ERRORS: ' + data.error);
                 }
             },
             error: function(jqXHR, textStatus, errorThrown)
             {
                 console.log('ERRORS: ' + textStatus);
             }
             complete: function(jqXHR, textStatus, errorThrown)
             {
                 // Notify the user that the upload process is complete!
             }
    });
})

You will need to handle UI interactions, as the file upload may be time consuming. There are 2 comments in the code that mark where UI interaction may be done. Commonly, this is to show or hide a spinner.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43