Vinsens
Vinsens

Reputation: 199

AJAX: combining upload file and text input code?

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?

I have code like this:

$("#save-sm").bind("click", function(event) {
  var url = "sm.input.php";

  var v_name_sm = $('input:text[name=name_sm]').val();

  // sending for process
  $.post(url, {name_sm: v_name_sm, id: id_sm} ,function() {

    // show data <div id="data-sm"></div>
    $("#data-sm").load(main);

    // hide modal dialog
    $('#dialog-sm').modal('hide');

  });
});

and I want add file upload script, like this one:

$("form#data").submit(function(){

  var formData = new FormData($(this)[0]);

  $.ajax({
    url: window.location.pathname,
    type: 'POST',
    data: formData,
    async: false,
    success: function (data) {
      alert(data)
    },
    cache: false,
    contentType: false,
    processData: false
  });

  return false;
});

how combining all code together so I can send both in once??

thanks :D


OK so, this is my final code:

$("#save-sm").bind("click", function(event) {

  var v_name_sm = $('input:text[name=name_sm]').val();
  var id_sm = "your variable";
  var formData = new FormData(document.getElementById("form-sm"));
  formData.append("name_sn",v_name_sm);
  formData.append("id",id_sm);

  $.ajax({
    url: 'sm.input.php',
    type: 'POST',
    data: formData,
    async: false,
    enctype: 'multipart/form-data',
    success: function () {
      // show data <div id="data-sm"></div>
      $("#data-sm").load(main);
      // hide modal dialog
      $('#dialog-sm').modal('hide');
    },
    cache: false,
    contentType: false,
    processData: false
  });

  return false;
});

Upvotes: 2

Views: 1467

Answers (1)

JuanSedano
JuanSedano

Reputation: 1025

You can try something like:

$("form#data").submit(function(){

  var v_name_sm = $('input:text[name=name_sm]').val();
  var id_sm = "your variable";
  var formData = new FormData($(this)[0]);
  formData.append("name_sn",v_name_sm);
  formData.append("id",id_sm);
  $.ajax({
    url: window.location.pathname,
    type: 'POST',
    data: formData,
    async: false,
    enctype: 'multipart/form-data',
    success: function (data) {
      alert(data)
    },
    cache: false,
    contentType: false,
    processData: false
  });

  return false;
});

Upvotes: 2

Related Questions