Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input type file not serialize jquery

I want to send form data using ajax done by serialize method but input type text and email is serialized in array but input type file not serialize in array

<form role="form" action="javascript:;" id="myform"  enctype = "multipart/form-data" method = "post">
        <div class="form-group">
          <label for="name">Name:</label>
          <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
        </div>
        <div class="form-group">
          <label for="email">Email:</label>
          <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
        </div>
        <div class="form-group">
          <label for="email">Photo:</label>
          <input type="file" name="userPhoto"  id="userPhoto" class="form-control"  />
        </div>
        <button type="submit" class="btn btn-default submit_add" id="enter">Submit</button>
      </form>

And Ajax Code

$('.submit_add').click(function(e){ 
          e.preventDefault();
          var data = $('#myform').serialize();

          console.log(data); return false;
          $.ajax({ 
              url: '/ajax',
              type: 'POST',
              cache: false, 
              data: data,
              dataType: 'json',
              success: function(data) {
                          if (data.success == true ) {
                            window.location.href  = '/';
                          } else {
                            alert('Error : There is something wrong.');
                          }
                        },
              error: function(jqXHR, textStatus, err){
                   alert('text status '+textStatus+', err '+err);
               }
          })
      }); 

Console response

name=manish+prajapati&email=kumar%40manish.com

like image 888
Manish Prajapati Avatar asked Jan 29 '26 14:01

Manish Prajapati


1 Answers

You should try this:

var data = new FormData($("#myform")[0]);

and set:

processData: false,
contentType: false,

See more here: http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/

like image 153
Henry Tran Avatar answered Jan 31 '26 04:01

Henry Tran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!