Should I use form to submit JSON data to REST api - javascript

Is it approved to use a html form to build interface to collect user data, convert it to domain model in front end and POST it to server using JSON?
I like to think the user input part as a logical form, event though the server expects JSON. For user it is all the same, so why not just to use a form to collect the data and implement a custom onSubmit method? Another option would be use detached input fields and buttons.
Is this considered a good practice to use forms for JSON POST and what are the good and bad consequences of this practice?

Here is my thought on this:
Pros:
Potentially you can re-use web services to perform form validation as well as acting as a standalone service. Make sure you really have this need before implementing this non-standard method.
Cons:
You are moving away from standard form/post models which is a basic feature of HTML for several years.
Your users will be forced to use JavaScript - not such a big deal in 2016 but you are losing accessibility for... what gain?
You will have to manage this requirement for multiple browsers (adds potential complexity).
Possibly the page load rank will be slower depending on your implementation. This might impact SEO and user experience.
I see a lot more cons thant pros, but maybe your situation truly justify this?

Grouping inputs and submit buttons within a <form> is semantic and good practice, it simply requires calling preventDefault on the event passed to your onSubmit handler to prevent the hard form submit. Your API should speak JSON, and it's trivial to save your form values into state values into state onBlur/onChange, and use jQuery or some other lib to create a JSON post. While its not completely necessary, I cannot think of drawbacks. Fallbacks for the "no javascript" scenario aren't realistic now for most use cases.

i think its a bad approach.
in client side, do client logic, ui logic, etc...
in server side do your processing.
also in many API you will need credentials/token...you sure you wanna share those on cliend scripts (: ??

Related

SPA POST/PUT data manually without a form - good practice or an anti-pattern

A question I could not find a trustworthy resource for online and so refer to the community,
in the past in JSP/PHP/ASP I would usually use and fields to post data, either for POST or PUT, now days I use React.js for comprehensive web-apps and usually do not use but only fields where required and POST them manually using Axios.
My question is if it is considered a possible approach where required (for example if there are many fields across the screen so prefer not to warp everything in one big ) or if the best approach is still to use a large to warp everything and submit POST/PUT data using the form submit function.
I am also aware of the option to handle the submit handler and use axios there but my question is if I have many different inputs around the screen, should I warp everything in a or I can simply POST data from the inputs onChange directly where appropriate.
One last comment - the purposes is not for an opinionated question/answer but for a YES/NO - possible & common design or not possible anti-pattern design.
Thank you!

In scala or scalajs Diode, do any of the existing types line up with the use case of "updating a model that doesn't yet exist"?

Here's a common situation: you have a form and you're interested in the submissions of that form. You may add a wrinkle to the situation by adding a server-side validator, or even a client-side validator, but the validators are only provided as a means of ensuring the input you submit is valid at that instance; any state collected between 0 and submission is thrown away and incidental.
Here's a less-common situation: your form has a password/confirm field that you need to wire to work in the obvious manner and wire to display an indication of password strength (and validity). In the past I've seen a lot of "write a jQuery callback for the event handler on change, and call it a day." This is just a more extreme case of needing the state in between to get to a destination, not as an end in itself.
Now a very uncommon situation: you need to track the input of this form because it is a form used by the US government to communicate with our guys in nuclear bunkers in Wyoming. It is certainly important that form input is valid on submission, but we need to additionally know as much as we can about the way it got there. Let's say it is a login form for instance. If we track the sequence of events from 0 to submission and compare it to the past we can detect anomalies in user behavior, for instance. We can determine whether we might be having login servers problems before we hear about them. So this is not always throwaway info.
I want to map the event onChange to some Diode concept, but I'm having trouble figuring out what I ought to do. Here are the options:
I could define a new case class for each field-type and for each object-type permuted, and stick all of them in the root model (seems like a stupid way to do it)
I could define a genericized data structure representing an "un-submitted change in input value" that would also indicate the model and field changing. Seems optimal but maybe unnecessary and a lot of work and hard to do well.
I could use an existing data structure, like one of the Pots, to stand in place for my Scratch data structure. Probably the best idea but not sure which to use.
That's where I am at... any thoughtful advice is appreciated.
This may be something where using a chat would work better, but here are some thoughts on the matter.
There are three places you could store such an event log:
In the state of the view component. Just add the timestamped events to a list stored in the view state. On submission, send this list alongside with the rest of the data.
In the Diode model. Again, store a list of events in the model and submit with the form data.
In the server. Send each event separately to the server and let it worry about what they mean. No need to store on client side at all.
For such transient data, I wouldn't route it through Diode at all, but instead use options 1 or 3 to transmit it.

Django saving models by JS rather than form submissions?

I have a contract job for editing a Django application, and Django is not my main framework to use, so I have a question regarding models in it.
The application I am editing has a form that each user can submit, and every single model in the application is edited directly through the form.
From this perspective, it seems every model is directly a form object, I do not see any model fields that I could use for custom variables. Meaning instead of a "string" that I could edit with JS, I only see a TextField where the only way it could be edited is by including it on a form directly.
If I wanted to have some models that were custom variables, meaning I controlled them entirely through JS rather than form submissions, how would I do that in Django?
I know I could, for example, have some "hidden" form objects that I manipulated with JS. But this solution sounds kind of hacky. Is there an intended way that I could go about this?
Thanks!
(Edit: It seems most responses do not know what I am referring to. Basically I want to allow the client to perform some special sorting functions etc, in which case I will need a few additional lists of data. But I do not want these to be visible to the user, and they will be altered exclusively by js.
Regarding the response of SColvin, I understand that the models are a representation of the database, but from how the application I am working on is designed, it looks as if the only way the models are being used is strictly through forms.
For example, every "string" is a "TextField", and lets say we made a string called "myField", the exclusive use of this field would be to use it in templates with the syntax {{ form.myField|attr:"rows:4" }}.
There are absolutely no use of this model outside of the forms. Every place you see it in the application, there is a form object. This is why I was under the impression that is the primary way to edit the data found in the models.
I did the Django tutorial prior to accepting this project but do not remember seeing any way to submit changes to models outside of the forms.
So more specifically what I would like to do in this case: Let's say I wanted to add a string to my models file, and this string will NOT be included/edited on the form. It will be invisible to the user. It will be modified browser-side by some .js functions, and I would like it to be saved along when submitting the rest of the form. What would be the intended method for going about doing this?
If anyone could please guide me to documentation or examples on how to do this, it would be greatly appreciated! )
(Edit2: No responses ever since the first edit? Not sure if this post is not appearing for anyone else. Still looking for an answer!)
There is some terminology confusion here, as SColvin points out; it's really not clear what you mean by "custom variables", and how those relates to models.
However your main confusion seems to be around forms. There is absolutely no requirement to use them: they are just one method of updating models. It is always possible to edit the models directly in code, and the data from that can of course come from Javascript if you want. The tutorial has good coverage of how to update a model from code without using a form.
If you're doing a lot of work via JS though, you probably want to look into the Django Rest Framework, which simplifies the process of converting Django model data to and from JSON to use in your client-side code. Again though DRF isn't doing anything you couldn't do manually in your own code, all without the use of forms.

Where should you validate/sanitize data?

I am building a traditional MVC app. I have a /lib folder that defines functions that deal with database operations and dealing with external APIs. When processing user input, where should I validate the data? Should I validate it in the route controllers and then send that validated data to the database functions? Or should I do no validation in the route controllers and have the functions in the /lib folder do all the validation?
For me the most natural place is in the model because it contains the data. The GRASP Expert Principle says that you should assign responsibilities to an object that has the information to fulfill them.
We could argue that the controller may have all the information (data) required to do the validation but for me controllers should be light. Moreover, I think that "all the information" means not only having the data you must validate, but also knowing its format, and that's the model's concern. The controller may know how the data that a certain model needs should be, but that model could also be used outside that controller scope, so it should not rely on the controller's validation to work well as the model is (almost) your last chance to detect invalid data (you can, and must, also do that on the database, but data should be validated and sanitised before it goes into it, although normally there's a direct match between the database schema and the validation you should do in the model).
Every time you do CRUD operations with a model you will probably need to validate the data and you will be ensuring that your data is almost always correct. Moreover, the controller could also change the data that then goes into that model, so even if the controller validated it previously, it may produce invalid data.
However, think about that. The controller may change the data and in fact a lot of time they do so. It is unusual to always have a direct map between the fields in a form and a model and sometimes you will have inputs that have nothing or little to do with any model, so you should validate them outside the model. For example, think about the "Repeat password" field. It has nothing to do with the model! Only the "Password" field should reach it.
Other people would say that they prefer anemic models and that may fit best than rich models in some scenarios, but they also have some drawbacks and rich ones fit best in general.
You should also consider having validation in the client side (i.e. JS) so that you can give him a fast feedback about what he is doing instead of sending the data to the server to be validated and then wait the response or even load the whole page again!
One good way to do that is to use regex because you will have similar expressions between the different languages that you are using, although more often than not that won't be enough. Or better, you could use JS everywhere with Node.js and totally forget about that problem.
This may not be the answer you was looking for, but there is not only one right way to do validation as it is different for each application. Most times, validation should occur in different places, doing the same validation in some different layers of your application and different validation between some others.
There are more questions about this topic on StackOverflow, so you could check them to have different opinions from other people:
Best Place for Validation in Model/View/Controller Model?
MVC Question: Should I put form validation rules in the controller or model?
MVC - User input validation: controller, model or both
Where should data validation occur?
One of the nicest approaches I've seen is to define services and layer validation over the top of them using decorators. If validation errors occur an custom exception is raised containing the validation errors which is caught and handled by the controller and sent back to the client.
Controllers should be thin, and deal with things like requests and responses rather than business logic. Whatever approach you use I'd advise trying to keep it decoupled from the controllers.

Connecting a form to a Javascript Object (and other best practice advice)

I've been using javascript to do lightweight functionality on sites for years - DOM manipulation etc - but just now im beginning to investigate using it to do a lot more of the heavy lifting (in combo with PHP). I've only just started getting into OO JS, and im still trying to get my head around the best-practices and design patterns that work well with it.
To be more specific - my question is, can anyone here suggest techniques for connecting a form to a javascript object?
In my current implementation I have an JS object that can be edited by a (fairly large) form. When I instantiate the object I attach an onchange observer to the form, whose callback syncs the form fields with the object parameters. I'm handling the form submitting through AJAX - there is also a periodic request that saves a temporary version of the form info to a mySQL DB. One thing I wonder is whether it is possible to easily handle syncing in the other direction - onchange of the object the form fields update (on form reset for instance).
I am interested to know if this approach is a correct/sensible one, and more generally I would be very interested to hear advice with regard to OOJS form handling.
Cheers in advance :)
(Im using Prototype btw)
You can use $("form").serialize(true);
http://www.prototypejs.org/api/form/serialize
You dont need the onchange event, you can just call the serialize() method every time you need to get the form data.
Why not create a method in you object that resyncs the object with the form? And call that on every change of the object? You could create a special change function to assure that it gets called on every change.
It's a perfectly reasonable approach. JS doesn't entirely encourage this sort of thing due to its curious object system and in particular the way bound methods are not first-class objects, but with a bit of suitable metaclass and callback glue it's eminently possible.
You might also want to look at a widget library if you'd like to get more of this kind of low-level form handling stuff for free. Haven't tried the ones built on top of Prototype; other possibilities include YUI's one.
Updating the model from the server can be pretty simple. Generally you'd poll an AJAX request and have the server pass back either diffs, if it knows them, or else just timestamp each object update, send the new object details to the client side on each update, and have the client decide how to merge that with any changes the user has made in the meantime.

Categories

Resources