Bahram
Bahram

Reputation: 87

How to send more data with formdata via AJAX

I want to send a multiple form-data via jquery ajax to PHP. What should I do if I want to send more values to PHP using the data-value-1="value1" and data-value-2="value2" into each input?

HTML

<form action="url.php">
<div><input type="text" class="title-input" name="titleInput" placeholder="title"></div>
<div><input id="file_input" name="files[]" class="img" type="file"/></div>
<input name="submit" type="submit" value="upload"/>
</form>

JavaScript

$(function){
  var form_data = new FormData(this); //Creates new FormData object
        var post_url = $(this).attr("action"); //get action URL of form

        //jQuery Ajax to Post form data
        $.ajax({
          url : post_url,
          type: "POST",
          data : form_data,
          contentType: false,
          cache: false,
          processData:false,
          xhr: function(){
            //upload Progress
           }

});

everything is good until I need this to send more values with data-val into the input tag.

<div>
  <input type="text" 
         class="title-input" 
         name="titleInput" 
         placeholder="title" 
         data-value-one="val1" 
         data-value-two="val2">
</div>

how can I send these values with form-data?

Upvotes: 1

Views: 535

Answers (1)

charlietfl
charlietfl

Reputation: 171700

Loop over elements that have data attributes, then iterate the data object that jQuery returns using data() and append() the key/values to the FormData object

$('form').submit(function(evt) {
  evt.preventDefault()
  var form_data = new FormData(this);

  $(this).find(':input').filter(function() {
    return $(this).data()
  }).each(function() {
    $.each($(this).data(), function(k, v) {
      form_data.append(k, v)
    });
  });
  
  console.log(Array.from(form_data.entries()))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="url.php">
  <div>
  <input 
      name="titleInput" 
      value="title test"
      data-value-one="val1" 
      data-value-two="val2"
  >
  </div>
 
 
 <div><input id="file_input" name="files[]" class="img" type="file" /></div>
  <input name="submit" type="submit" value="upload" />
</form>

Upvotes: 2

Related Questions