简体   繁体   中英

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

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/

I use jquery (but this can be easily done via vanilla javascript too) to create a hidden text input after the file input. I then set the name of the new text input as the id of the file input it's associated with and set it's value (when a file is selected) to the filename. You can then use $('form').serializeArray(); and return the name:value pairs of the hidden inputs that correspond to the file inputs.

 /* The javascript/jquery */ $(document).ready(function(){ // Dynamically create hidden text inputs for the file inputs' data // (create dynamically to avoid having re-write your entire html file) $('input:file').each( function(){ $(this).after('<input type="text" readonly name="' + $(this).attr("id").replace("_", " ") + '" hidden value=""/>'); }); // When the user selects a file to be uploaded... $('input:file').change( function(){ // If a file is selected set the text input value as the filename if($(this).get(0).files.length !== 0){ $(this).next('input:text').val($(this).get(0).files[0].name); } }); $("form").submit( function(e){ e.preventDefault(); //Clear previous data from results div $('#results').text(""); // Serialize the form data var x = $('form').serializeArray(); // Iterate through the array results and append // the data to the results div $.each(x, function(i, field) { var result = '<span class="left">' + field.name + ' : </span>'; result += '<span class="right">' + field.value + '</span><br>'; $('#results').append(result); }); }); }); 
 /* The .css */ form { display: inline-block; left: 0; width: auto; max-width: 40%; margin-left: 0; padding: 0; } div.left, div.right, span.left, span.right { display:block; position: relative; width: 40%; } .rad { font-size: 14px; } .left { float: left; } .right { float: right; } #results { display: inline-block; position: relative; width: auto; min-width: 40%; line-height: 23px; } #results .left { color: green; text-align: right; } #results .right { color: blue; text-align: left; margin-right: 20px; } .clearfix { clear: both; } 
 <!-- The HTML --> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <form id="myForm"> <div class="left"> <label class="right" for="name">Name:</label><br> <label class="right" for="gender">Gender:</label><br> <label class="right" for="file1">1st Pic:</label><br> <label class="right" for="file2">2nd Pic:</label><br> <label class="right" for="file3">3rd Pic:</label><br> <label class="right" for="file4">4th Pic:</label><br> </div> <div class="right"> <input class="left" type="text" name="Name" ><br> <select class="left" name="Gender"> <option selected></option> <option>Unspecified</option> <option>Female</option> <option>Male</option> </select><br> <input class="left" type="file" accept="image/*" id="File_1"><br> <input class="left" type="file" accept="image/*" id="File_2"><br> <input class="left" type="file" accept="image/*" id="File_3"><br> <input class="left" type="file" accept="image/*" id="File_4"><br> </div> </form> <div id="results" class="right"></div> <div class="clearfix"></div> <input form="myForm" type="submit" id="submit" value="Serialize Form" /> <input form="myForm" type="reset" value="Reset Form" onClick="this.form.reset()" /> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM