Rails 5: Submitting multiple forms with one submit button best practice - javascript

I am building a survey-like rails application. The survey has several particular sections (several views) and in each section there are multiple questions. The user will answer those question (free text) and at the bottom of every section view there should be one submit button that saves all entries.
The model for the user answers is:
user_answers(id:integer, user_answer:string, user_project_id:integer, question_id:integer).
The user_answers have a user_project_id to associate it with their created project and a question_id for a an answer. That way the answers later can be directly associated to the right user project and the corresponding question.
What is best practice to save multiple entries/form_for :user_answers with one submit button at the end of the page?
I read about the javascript method Submit two forms with one button, but I fear if the entries are not saved asynchronously it could lead to errors
Sidekiq could be used to do the jobs asynchronously in the background.
Are there maybe other easier ways to do it?
Thank you in advance!

I actually found out that both are not applicable and the answer to my question was server-side rendering with fields_for.
Before I explain fields_for I want to answer why my strategies from above are not relevant.
Submit two forms with one button works, but renders everything client-side. That means it worked on my local machine, but as soon as I deployed the app on heroku and tried it, the javascript would not save all the records because the browser would terminate the JS after the first (or the first few) submit() actions.
is just a service to outsource workload. That would not solve the problem of inconsistent database records.
So I needed to find a way to process the records server-side, and that is fields_for: https://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for.
It allows you to save multiple nested objects by putting it into a "parent"-form_for.
Here is a good tutorial to get a look and feel: https://www.youtube.com/watch?v=PYYwjTlcoa4
In my case, I made a "shell" form_for as a container around the fields_for. The fields_for in my code were dynamically generated according to the number of questions in the database. By submitting the shell form_for, I was able to process all fields_for answers to my survey server-side with one click.

Related

Saving data during web session

If I need to save a user’s data on which buttons they clicked while they visited our website, and without uploading a database would these be some of the ways? The problem is any array I have at that moment is reset everytime the user is redirected from the page.
Disclaimer: I’m new to PHP
PHP class. Create necessary push/pop features for an array and pass that class instance throughout the code. I tried this before but was having the issue of the array being reset no matter where I placed the code. Originally I had it on the header that is at the top of all pages but again this wasn’t the solution.
Localstorags through JavaScript. Haven’t used this yet as there has to be a better solution.
Upload to database Again, haven’t used this but there has to be a better solution as multiple MySQLi queries will surely be taxing.
Cheers!
Not sure why you don't want to use localStorage.setItem('clicks', JSON.stringify(array));
Depends on how big your array gets but should not be a problem for some clicks really.

How to save a dynamic web page (Cordova App)

I created an App for projects and To Do lists. It consists of one HTML page, which only has an "add To Do list"-button.
The user can click on that button and create a To Do list, in this list he can create tasks.
The lists and tasks are dynamically generated HTML Elements.
Is there a way to just store everything, the dynamically generated DOM and all its elements and their functions? I searched for an answer for hours and all I found was a method to store data locally with localStorage: http://docs.phonegap.com/en/1.2.0/phonegap_storage_storage.md.html#localStorage
Since my elements contain a lot of js functions, it would be very complicated to store everything with this method...
Is there no way of storing "the whole thing"?
Thanks in advance!
Your question require a very large explanation, anyway I would tell you some tips you can use to step forward since I worked on a similar app last year.
Think about a database structure for your app. I got a table "Tasks" in which I stored both tasks and subtasks (task inside other tasks). I also stored alarms (if a task need an alarm), texts, checked/unchecked, archived flag, deleted flag, and so on. Everything you can associate to a task, you need a column for it.
Think about your data amount globally. If you plan to store a large amount of data (more or less 5MB) you better choose SQLite approach. If you think your data will not reach this edge, think about LocalStorage. You can google both to manage their use.
When the user fill the DOM to create a task and click on "create" (or something similar), you have to "scan" the DOM, acquire all info for the task created and put them into your DB
When the user want to update/modify a task, you have to find it in the DB, fetch related data, create the DOM's structures you need to show data, fill the structures with data
These are more or less few tips I can give you on your long way. Good luck

Handle action of drop-down-list in javascript and php in the same form

I am trying to create a set of dropdown boxes that are interconnected using PHP and JavaScript.
My objective is to read an input value from a dropdown box, and use it to determine the values of other dropdown boxes.
An example of this is a dropdown list for States where the user takes the following actions:
Choose a State
Choose the province within that State
Choose the city within that province
I wish to do something like this, but reading value from the Database and use the afore mentioned techonologies.
Database queries are executed by PHP. PHP is executed on the server-side.
HTML is rendered on the client-side, which is where user interactions take place.
So to get information from the database based on user interaction, you need to make an HTTP request to get information back from the server.
To do this, you would use AJAX. Read up on that for the solution to your problem.
Without specifying any libraries that you are using one can only guess. However, after a quick search, I recommend the following plugin:
http://www.cssscript.com/generic-country-state-dropdown-list-countries-js/
Github also has a very interesting project regarding this:
https://github.com/mrmarkfrench/country-select-js
These solutions will help you avoid the need to use a DB. However, if you really need to do it, then you have to use AJAX and make at least a request to the server.
Overall if you use a library like jQuery or a Framework like Angular things can be easier, but you can still manage with what you have.
Hope it helps!

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.

mvc approach with javascript / jquery no framework

I'm developing a large scale application. Initially my approach was confused , I am a beginner in javascript even if I develop since January.
I was looking for an mvc approach and I found some guide lines, like :
Model : contains AJAX call , and services
Controller: e.g. jQuery widget and so on
View: e.g. rendering of HTML and so on..
I don't really have clearly how to structure a javascript application following perfectly the three above suggestions. I can do everything, I can manage template I can write jQuery manipulation , I can do AJAX call.
What is not clear to me is how to get really divided these three modules. When I try this approach I'm not able to make any module to do only what it has to do.
I tried also an MV* approach which, for what I see and for my needs maybe it's a better approach, because I have to do bind tons of divs , generate events , all by client side, receiving only data from server side.
What I would like to know:
Which are the really competences of each Module?
If, for example, I have to bind a click event to a button , where do I have to write the
.on('click',callback)
method? Where I have to write the callback he's gonna call?
I wrote : no framework because I'm sure that if I don't understand an approach writing it from scratch, its impossibile I will completely understand the use of a complete framework.
I hope that my doubts were clear, if not, please comment, I'll try to explain better if I can.
Sorry for my english in any case.
This is not an answer because there is no one answer. I just want to mention a few do's and don't's.
Do store pure data in the model. Think of it as business objects rather than display objects. For example, money should be stored in the model as a number, probably with some digits after the decimal point, plus an indicator of what currency it is, if that matters. Don't store the number as a string with local choices of the characters to separate the 1000's and the integer part from the fractional part and the right number of digits after the decimal point.
Do put the handler code for the click events (and similar user actions) in the controller.
Do put the code that causes updates the screen on load or on any external event in the controller. (An external event might be something like an update to a stock price due to stock exchange data or an update to the weather report coming into the application.)
Do put the HTML or the code that generates HTML as part of the view.
Do have the controller call the view to get the display updated/changed at the right times.
Do have either the controller or the view call the model to get the current model data values or the update the the current model data. (See similar "don't" below.)
Do reduce the connectivity between the three parts--M, V and C. Define clearly who can talk to whom for what purpose and keep that rule sacred. If you find an exception, its a smell indicating a problem with the big picture of those rules.
And some more things
Don't put the code that displays the screen on load in the controller. That's clearly a view concern. This means the controller has to call into the view somehow.
Don't spaghetti connect the M, V and C code in random fashions. For example, you might make a rule that the model never calls code in the view or controller.
Don't have both the controller and the view talking to the model.
Questions:
Where does the code go that hooks up the event handlers?
Where do you put the "business logic"? This is the code that knows the rules of your application. Validation, for example, is business logic. Some code may need to know how zip codes look for the US and postal codes for the UK or Canada. If the validation fails, the controller is the one that tells the view to show an error message or red mark or vibrating box or whatever. Does the business logic of validation rules also go in the controller?
Where does the code go that loads data from external data sources? (servers, JSON web services, databases, screen scraping, etc.) You might think "model" but then the model has to call into the controller when new data comes back to tell it to update the view. That doesn't seem right.
Similarly, what is the code that handles the equivalent of a "submit" button, moving to another screen.
If converting data from a form that is displayable on the screen to a form that is pure data is too slow, what do you do?
There are always self-contained portions of the screen that can be built with their own MV&C. How do you set up interactions between multiples of those little MVCs and the big MVC that is the whole screen? Are those little guys the views for the big MVC? Or are the controllers? Can they be both at once? Is there a big model with the little models in it or does data flow between little models and big models? Who knows about all this?
Is there an even bigger MVC comprised of multiple screens? It would probably be on the server if it exists.
How do you handle "synthetic" events? This is something like an "event" that occurs when the data was ok but is now in a bad state (or was incomplete and is now complete). Listeners to this event can disable the "Submit" button and display error messages or animations calling the user attention to the problem. It could be anything that isn't a generic event built into the framework or language. Perhaps its a message to the server indicating a change in the state of a multiplayer game's world view.
This is just a list of things that pop to mind when you are writing your own MVC or when evaluating an existing framework.
There is no clear answer outside a specific framework. Although the general responsibilities of the MVC pattern are (almost) clear to everyone, each framework has its own interpretation of exactly what pieces of code to put in each of these layers - some frameworks even skip some layers, or add different ones instead.
I know you don't want to use a framework, but still, it's worth to have an overview of how the current solutions work, so you can make an informed decision if you like the way they work or if you prefer to roll your own.
I recommend you at least take a look at one server side MVC framework (such as Ruby on Rails or Asp.Net MVC) and some client side MVC frameworks too (Backbone.js, Angular.js, etc. - javascript only). Read their documentations, and learn from the choices others have made (and tested). The site todo mvc can help you to compare different client MVC frameworks to find the approach you like better.
This is not a simple topic, and discussing the pros and cons of each approach from scratch can take forever.

Categories

Resources