0

I am trying to upload image after form submit using ajax call, having an issue that annoying me, the new FormData($(this)[0]) gives me actual values, but whenever I try to send it through ajax its malfunctioning and reloads the page, so I cant see the console as well, please correct me where I am wrong.

My javascript code

$("#editImage").submit(function(){
var data = new FormData($(this)[0]);
console.log(data);
return false;
$.post("../galImages", data).done(function(response){
    console.log(response);
});
return false;});

My HTML code

<form name="edit-image" id="editImage" action="" method="post" enctype="multipart/form-data"><input type="file" name="change-image" accept="image/*" class="form-control mb-20" value="Upload Image">
                    <input type="hidden" name="edit-img-id" id="editImageId"><input type="submit" class="btn btn-primary" value="Save Changes" id="submitEditImgForm"></form>

however file datas are posted in the PHP page, and one more thing how can I send hidden field value along with formdata object. I am a noobie in ajax $.post method. Please help me if anyone have any idea.

Rajesh Dey
  • 153
  • 2
  • 13

2 Answers2

1

As you upload an image (my mistake, forgot that first!) : Important parts are the ones needed for upload otherwise it will fail

$(function () {
$('#my_form').on('submit', function (e) {
    e.preventDefault();

    var $form = $(this);
    var formdata = (window.FormData) ? new FormData($form[0]) : null;
    var data = (formdata !== null) ? formdata : $form.serialize();

    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        contentType: false, // needed for upload
        processData: false, // needed for upload
        dataType: 'json', // return
        data: data,
        success: function (response) {
            // response
        }
     });
   });
});

This code is not mine, found it, adapted it long time ago, can't credit its original owner as I don't remember who she/he is :/

OldPadawan
  • 1,247
  • 3
  • 16
  • 25
  • UR welcome. Good code for the future, and sorry for the mate who 'gave' us this portion of code and won't get credit for it... – OldPadawan Apr 14 '17 at 19:06
0

Use preventDefault() this will prevent the default behaviour of the form and the page from reloading.

$("#editImage").submit(function (e) {
    e.preventDefault();
    var data = new FormData($(this)[0]);
    console.log(data);
    return false;
    $.post("../galImages", data).done(function (response) {
        console.log(response);
    });
    return false;
});
Junius L
  • 15,881
  • 6
  • 52
  • 96
  • Thank you @julekgwa, seems like its working, page stops reloading but there is an error in console.log, `Illegal invocation`, that prevents the page to send data to the destination php file – Rajesh Dey Apr 14 '17 at 18:49