Satyadev Satyadev - 2 months ago 11
Ajax Question

unable to post data using jquery ajax

I am able fetch the json data using the form below:

<form enctype="multipart/form-data" action="http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile" method="post">
<input id="default_file" name="file" type="file" />
<input id="account" name="account" type="hidden" value="testing" />
<input type="submit" value="Save">
</form>


but the same form when used with jquery ajax is throwing error:
501 (Not Implemented)


$('#default_file').change(function (e) {
//on change event
formdata = new FormData();
if ($(this).prop('files').length > 0)
{
file = $(this).prop('files')[0];
formdata.append("music", file);
}
});


function hitexternal(e) {
$.ajax({
url: "http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile",
type: "POST",
data: new FormData($("#default_file")[0], {data :{"account":"testing"}}),
processData: false,
contentType: 'application/json',
success: function (response) {
console.log('resp: ' , response);
},
error: function (jqXHR, textStatus, errorMessage) {
console.log("error:" , errorMessage);
}
});
e.preventDefault();
}


What did I miss here?

Answer

Remove the content type FormData takes as input the form and converts it into key/value pairs

function hitexternal(e) {
    var formdata =  new FormData($("form")[0]);
    $.ajax({
        url: "http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile",
        type: "POST",
        data: formdata ,
        processData: false,
        contentType: 'multipart/form-data', // or set it as false to let jquery chose the right one for you
        success: function (response) {
            console.log('resp: ' , response);
        },
        error: function (jqXHR, textStatus, errorMessage) {
            console.log("error:" , errorMessage);
        }
    });
    e.preventDefault();
Comments