1

Here I have used serialize method to fetch the data but I am not getting image from that please help to find the solution or give me alternative of serialize method.

$( "#button" ).click(function(){
    $.ajax({
        type: 'POST',
        url: ajax_url,
        enctype: 'multipart/form-data',     
        data:{

            data_array:$( "#form" ).serialize(),
            action: 'product_add_form_submit'
        },
        success: function (data) {
            alert('Successfully Submitted');
        }
    });
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
S.S
  • 59
  • 1
  • 2
  • 7
  • I think this link can help [http://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax](http://stackoverflow.com/questions/10899384/uploading-both-data-and-files-in-one-form-using-ajax) – DsRaj Aug 11 '16 at 11:35

3 Answers3

3

You can upload Form fields with file as mentioned below, and follow comment.

$('#my-form').submit( function( e ) {
    form_data= new FormData($(this)[0]);
    var imgFile = $("file_input_selector")[0]; // change your delector here
    form_data.append("file_name_field", imgFile.files[0]); // change filename field here
    $.ajax({
        url: 'http://host.com/action/',
        type: 'POST',
        data: form_data,
        success: function(data){
            alert(data);
        }
    });
    e.preventDefault();
});
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
  • Its glad to hear its working.. thanks for mark as correct.. if you like this please up vote it, now you have enough reputation ;) – Haresh Vidja Aug 12 '16 at 05:58
1
( '#my-form' )
  .submit( function( e ) {
    $.ajax( {
      url: 'http://host.com/action/',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();
  } );
0
//html form

<form action="url" id="addquestionsamepage" class="form-horizontal form-label-left" method="post" enctype="multipart/form-data" accept-charset="utf-8">        

<div class="item form-group">
    <label class="control-label col-md-3 col-sm-3 col-xs-12">Image </label>
    <div class="col-md-6 col-sm-6 col-xs-12">
        <input  class="form-control col-md-7 col-xs-12"  name="image"  id="add_image" type="file">
    </div>
</div>

</form> 

  

//jquery code

$('#addquestionsamepage').submit(function (e) {
        e.preventDefault();
        var form = $("#addquestionsamepage");
        var url = form.attr('action');
        var formData = new FormData(this);
        $.ajax({
            type: "POST",
            url: url,
            data: formData,
            cache:false,
             contentType: false,
             processData: false,
            success: function (data) {
               alert(data);  
            },
            error: function (data) {
               alert(data);
            }
        });
    });
Anil Tomar
  • 82
  • 4