2

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;
});
3
  • Put the text box in the from and use the second piece of code. Commented Jan 20, 2015 at 15:10
  • so I dont need jQuery $.post again? Commented Jan 20, 2015 at 15:14
  • When you use new FormData(a_form); all the fields in the from will be posted. Commented Jan 20, 2015 at 15:15

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.