9

I have a function which does some custom work on form submit, send some data via Ajax, append the returned data in a new FormData object, now I need to submit the form conventionally (not via Ajax) with this FormData. I understand that it can be achieved with hidden fields, but what if I don't want the returned data to be visible to someone who knows a little bit of coding ?

So is it possible to submit a form with a custom FormData in jQuery without the hidden fields and Ajax ?

StudentX
  • 2,063
  • 4
  • 30
  • 61
  • are we looking for something like this: `$("#form-id").submit()` ? – Coding Enthusiast Aug 14 '15 at 16:39
  • 1
    @CodingEnthusiast No, submit() won't send the custom FormData object created programmatically. – StudentX Aug 14 '15 at 16:42
  • I'm not 100% sure what you are trying to do here, but it sounds like [session storage](https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage) may work, or at least be less visible than hidden fields – Michael Doye Aug 14 '15 at 16:54
  • Do u got any solution for this?? i'm also looking for something like this. If you are able to solve this issue can you please share the solution with us? – Zammuuz Jul 27 '16 at 05:25

3 Answers3

1

You could add your object into the form before submitting it and the remove it directly afterwards.

$('#yourForm').submit(function() {
    $(this).append(yourCustomObject)
    $(this).submit();
    $(yourCustomObject).remove();
});
Jens Hunt
  • 36
  • 4
1

At the moment, as you cannot call the submit event from a FormData object is to:

  1. intercept the original submit event preventing the default submit behaviour
  2. copy the original form to a new FormData instance (everything will be copied)
  3. use jquery ajax or native XHR in order to call the server action Please note that the ajax call effect has the same of an ajax/xhr call, using the correct configuration.
1

I found the answer sort of from this answer. If you don't already have a form you can create one as in the other post. In my case I had an existing form so I handled it in the submit event.

  $('form').on('submit',e => {

    formData['caption'] = $('#caption').val()
    formData['action']  = 'create'

    $.each(formData,(key,value) => {

      let field = $('<input></input>')

      field.attr("type", "hidden")
      field.attr("name", key)
      field.attr("value", value)

      $('form').append(field)
    })
  })

Just for reference I mutated the formData from another event in the document.

Keep in mind that the form will be submitted immediately after these fields are created as opposed to fetching that data and adding in as hidden fields on the form, so the data will not be part of the form for long before it is submitted.

decapo
  • 689
  • 2
  • 7
  • 19