Home > Enterprise >  how to use formData and closest functions together?
how to use formData and closest functions together?

Time:05-27

I am using two jquery/ajax functions to submit data, for the pages with single forms and file upload in it I am using var formData = new FormData(this);.

But I have multiple forms in some pages so I have to change function to var form = $(this).closest('form');.

My question is : How can I use closest(); function with formData in same function ? Then I can use same function for all pages instead using multiple functions.

Here is my function can be used with multiple forms but doesnt post files.

$(document).ready(function() {
   $('.submit').on("click", function(e) {
    e.preventDefault();
      var form = $(this).closest('form');
    $.ajax({
      type:'POST',
      url:'../page',
      data:form.serialize(),
      success:function(vardata){

        var json = JSON.parse(vardata);

        if(json.status == 101){
         alert(json.msg);
         window.location.replace("/my-account/");
        } else {
          alert(json.msg);
          console.log(json.msg);
        }
      }
    });
  });
});

And function with formData which is sending files but cant be used with multiple forms in same page.

  $("#ProForm").submit(function(e){
    e.preventDefault();    
    var formData = new FormData(this);
    $.ajax({
    url:'page.php',
    type: 'POST',
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
      success: function(data) {
        var json = JSON.parse(data);
        if(json.status == 101){
          alert(json.msg);
          window.location.replace("/my-account/");
        } else {
          alert(json.msg);
          console.log(json.msg);
        }
      }
    });
  });

I tried this but didnt work FormData(this).closest(); and append();

CodePudding user response:

a jQuery object is an array-like object where DOM nodes are values. So if you have a jQuery object with a single-use $node[0].

So I think that you want:

var form = $(this).closest('form');
var formData = new FormData(form[0]);

You can also use array destructuring:

var [form] = $(this).closest('form');
var formData = new FormData(form);
  • Related