Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change form data before sending it?

I'd like to find any generic method to change data before sending forms. It is, if I have a <form> that contains a <input> of certain type (class) and user press send button, I'd like to transform this input value to another format so it arrive to server in a corrected format.

I know I can set a submit() handler to process data, but I need a generic solution that setup this mechanism on load on all page forms and forgets about it (perhaps some forms are sent by AJAX, other use Jquery.validate to send, etc)

like image 426
Ivan Avatar asked Oct 11 '11 18:10

Ivan


People also ask

How do I move data from one form to another?

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.

Is form data sent in body?

There is no way to send a FormData object as the body and not sending data in the multipart/form-data format. If you want to send the data as application/x-www-form-urlencoded you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams object.

Which methods are used to submit form data?

Sending the form data using the 'POST' HTTP method: The POST method is used to send data to a server to create and update a resource.


1 Answers

Use jQuery's to select all form elements: $('form') and register a handler for the form submit event. Something like this:

$('form').submit(function(e){
    e.preventDefault()
    var $this = $(this)
    var formData = $this.serialize()
    // do some thing to it
    var yourData = transform(formData)
    $.ajax({
       post: $this.attr('action'),
       data: yourData,
       ...
    })
})

References

  • submit()
  • jQuery CSS Selector
  • Form serialize()
like image 90
airportyh Avatar answered Sep 28 '22 01:09

airportyh