I need to submit a form using jQuery but before it's submitted I want to change the value of one of the form fields without showing the change to the user. I know it's not the best way but my software demands that.
Currently I use:
var submit = $("#submitform").serialize();
To serialize data and then submit them using
$.post('/post', submit)
The serialized data I have are:
entry%5Bbody%5D=hello+and+welcome&addedContexts=presentation&context=prese ntation&selectedContexts=&statementid=×tamp=
I simply want to change the value of entry%5Bbody%5D
to something else.
I know I could use Regex on the string (I can't find which?), but maybe you know of a more elegant solution? Such as first serializing the form, then deserializing it, changing the value I need, and serializing it again?
Thanks!
serialize returns a URL-encoded string containing the form fields. If you need to append to it, you do so using the standard URL-encoded string rules, e.g.: var values = $("#frmblog"). serialize(); values += "&content=" + encodeURIComponent(content_val);
To get the POST values from serializeArray in PHP, use the serializeArray() method. The serializeArray( ) method serializes all forms and form elements like the . serialize() method but returns a JSON data structure for you to work with.
To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.
jQuery serialize() Method The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
Use $("#submitform").serializeArray()
and search for the item in the array with the name
property equal to "entry[body]"
and edit its value
property.
// convert form data to array
var data = $("#submitform").serializeArray();
// edit data here
// using ES6
data.find(item => item.name === 'entry[body]').value = "something else";
// OR using ES5
data.forEach(function (item) {
if (item.name === 'entry[body]') {
item.value = "something else";
}
});
// then POST
$.post('/post', $.param(data));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With