An example of the value of this is lets say you want to post, via ajax the values of multiple text input elements to the php/server. For example maybe you want to validate the an input textboxes minlength
and maxlength
property values are enforced at the server level, simply because its easy for someone to alter and manipulate things on a web page via Google inspect.
Normally when submitting a forms elements values to the server we think mainly of the elements name="" property and its value. For example, when using the formData() object ...
But what if we want the server to have more data about each of the elements, like as previously mentioned minlength
and maxlength
?
The answer is our good ole friendly function JSON.stringify which converts a Javascript object into a string. We will assume that the input elements we want to post to the server the ones with the class="send" have a minlength
and maxlength
property minlength="5" maxlength="15"
Let's assume the element values we want to submit to the server via Ajax look like this:
Here is how to do that.
If we run the following Javascript code to view what the formData looks like ...
We will see something like this:
While the first method to post multiple parameters to the server meets more with the coding purists approval, this second method of posting multiple data to the server meets more with my approval because it is just simple and there is less code.
This second method simply involves separating each of the parameters you with to ajax post to the server with a pipe character |
.
Processing this ajax submission via php at the server is also easiers.
My personal opinion is the second way is just a whole lot simpler and easier to understand and maintain and is a lot less lines of code as well.