andrejmonteiro
andrejmonteiro

Reputation: 67

Append jquery object to formData()

I'm currently developing a back office for some website, and I've come across some problems with file and information insert into databases. First I cannot upload a file and information in the same form without having to declare a variable for every other input, and second cannot append the declared object, like I always do, to the upload file form.

I've tried appending as and object but some of the inputs get undefined indexes.

This is the code i tried, to append an object to formData():

$(document).ready(function() {
 $('#addinfo-form').submit(function(e) {
  var info = {
   'name':$('#name').val(),
   'email':$('#email').val(),
   'country':$('#country :selected').val()
  }
  var file = $('#file').prop('files')[0];
  var new_info = new formData();
  new_info.append('info', info);
  new_info.append('file', file;
  $.ajax({
   type:'POST',
   url:'add-info.php',
   data:new_info,
   dataType:'json',
   processData:false,
   contentType:false,
   encode:true,
  }
  .done(function(data) {
  })
  .fail(function(data) {
  });
  e.preventDefault();
 });
});

Expected outcome should send info to php file via json to then be processed and inserted in the database.

Upvotes: 0

Views: 1506

Answers (2)

Kingsley
Kingsley

Reputation: 805

Alternatively, you could use Object.entries() such that your code now becomes...

$(document).ready(function() {
 $('#addinfo-form').submit(function(e) {
  var file = $('#file').prop('files')[0];
  var info = {
   'name':$('#name').val(),
   'email':$('#email').val(),
   'country':$('#country :selected').val(),
   'file': file
  }
  var new_info = new formData();
  Object.entries(info).forEach(([key, value]) => {
    new_info.append(key, value);
  });
  $.ajax({
   type:'POST',
   url:'add-info.php',
   data:new_info,
   dataType:'json',
   processData:false,
   contentType:false,
   encode:true,
  }
  .done(function(data) {
  })
  .fail(function(data) {
  });
  e.preventDefault();
 });
});

You first grab the file, add it as a property to your info object and parse it to formData.

Upvotes: 0

Manzolo
Manzolo

Reputation: 1959

Try this:

var info = {
    'name': $('#name').val(),
    'email': $('#email').val(),
    'country': $('#country').val()
};

var file = $('#file').prop('files')[0];
var new_info = new FormData();
new_info.append("file", file, file.name);
new_info.append("info", JSON.stringify(info));

$.ajax({
type:'POST',
        url:'add-info.php',
        data:new_info,
        dataType:'json',
        processData:false,
        contentType:false,
        encode:true,
 /*....*/

in your add-info.php

if (isset($_POST['info'])) {
    $info = json_decode($_POST['info'], true);
    echo $info["name"];
    echo $info["email"];
    echo $info["country"];
}

Upvotes: 1

Related Questions