Multiple part form - update database each submission - javascript

I'm sure this isn't the hardest issue to overcome, but I have a lack of understanding on how to handle this particular situation.
Learning MongoDB, Express, Angular, Node to create a web application for learning purposes.
I have a 2 stage submission form.
Step 1: Pet info is collected. text based input (pet name, pet description... ).
Submission of this info goes through my client side controller. Processed and saved to mongo as a new entry.
Step 2: Using ng-show/ng-hide, the first form is hidden and a second input form is shown for submitting an image.
Step 2 upload doesn't use a client side controller. Instead I make a direct method=post call to my express route. Multer module is called as middleware to upload my picture to a server side directory and generate JSON image info.
All I want to do is follow up with an update to mongoDB to insert the multer image_path into my previous mongodb collection, so that I can later render the image directly from the upload folder.
My issue is that I can't figure out how to pass the "_id" of the first steps submission to the 2nd step, so that I can perform the update.
How does one go about passing data that I have in my client side controller to my server side controller.
Can I use my view or do I need to call another express route to pass the data?
My project resides at https://github.com/astemborskim/anidopt.git
Currently working out of the temp branch.
Also posting the view, client side and server side controllers in the following gist.
https://gist.github.com/astemborskim/edc5d4a80dfe6e154c99

Here is one possible way of doing multiple part form.
You can use Bootstrap and use Tagglable Tabs
You can always customize it to your liking. Maybe hide or redesign tabs to look like a step. Then have your part one form submit/next button to toggle the second tab
Each tab will represent you form part
Now, when you submit you first part, you will get the _id back
and can use it for further requests

Related

Dump state into json or tsv (backend)

Many of the tutorials for survey / forms in React tend to cover front-end mechanics only. In my case, I pretty much have the front-end where I want it but have come to realize I know virtually nothing about back-end programming.
I thought it best to take baby steps, so maybe adding a line to a json/tsv after the user clicks a button would be a reasonable goal. I'm imagining the user manipulates all the bells and whistles I have then once he/she clicks "submit" then a new row is added to a "master_data.tsv" file on the back end.
Just for illustration, the portion of the state I would like to save is:
state = {
selectBoxes: [
{id:1, strategies:['Strat1','Strat2', 'Strat3','Strat4','Strat5']},
]
For context, this state gets passed down to drop-down menu components that have event listeners to record the user's choice. I have it so that the state is updated to reflect the user's desired choice. But I have not figured out how to dump the data on the back end once the choice is selected and the user click's "submit."
Question
Assuming click-flow:
Toggle dropdown menu -> choose item -> click "submit" button
How would I add a new row to master_data.tsv after each "submit" event?
(can ignore unique user qualification and all the fancy stuff, maybe we can settle for each new row has an id though. )
I would recommend taking a step back and first, thinking about the actual flow and data persistence of your application.
I would recommend creating a backend server (any language) that offers you to post the data to it via an API endpoint (usually a REST API with a POST endpoint)
After you receive your data, you have to persist it. Either in a database, in a session or on disk.
The last step is to retrieve the data in the desired format (tsv).
Either create another endpoint to return the data, or return the entire file already on POST.
Here is an example flow of how it could look like
Front-End: Send data on submitting to the backend (POST /entries)
Backend: Receive data and store it (disk, database …)
Front-End: Receive data from backend (GET /entries)
Backend: Returns entries as tsv
This way you are rather flexible and decoupled. Later on, you could exchange the format easily to JSON, XML, CSV …
Your source of truth should always be your storage layer (database, file on disk)

How do I write to an HTML file using expressjs

Ok, this sounds crazy, but let me explain. I want a user to be able to push a button, and then the html file is edited in such a way that it a NEW p element is created, and stays there PERMENENTLY (eg on reload and for EVERYONE to see). Any way on how I could do that.
Again I am using node.js/express, and html/js/css.
It really depends upon exactly what you're doing.
Conceptually, you would probably use some sort of template system for generating your HTML files (like Jade, Dust, EJS, Handlebars, Nunjucks, PUG, etc..) and then you store some state in a database and use a query from the database as input to the template whenever you render a particular page.
So, when you add an item to the database, it will show up in all future renders of the page.
So, your button would trigger a form post to your server which would add an item to the database and the response from the form post would be a rendering of the page after adding the item to the database. All future renders of the page from all users would also show those same items in the rendered page.

Cache API with MVC Views

I have a basic MVC form and I've been trying to use the Javascript Cache API to cache all my css, js, html files so that when users (people in the field) do not have reliable access, they can still use my web form. Obviously I'm using IndexedDB and service workers as well to check for a connection and save locally when a connection is not available, syncing when it is available.
I've gone through some tutorials and everything seems straightforward when dealing with caching actual, physical files (css, html, js). MVC is weird though since you're routing. I created the basix Index, Create, Edit, Details views. When I create an array of URL's to cache such as
var urlsToCache = [
'/App/Details',
'/App/Edit',
'/App/Create',
'/App/Index',
'/App/Content/bootstrap.css',
'/App/Content/site.css',
'/App/Scripts/jquery-1.10.2.js',
'/App/Scripts/jquery.form.js',
'/App/sw.js',
'/App/Scripts/bootstrap.js',
]
.. everything caches except for DETAILS and EDIT. Index and create cache fine. I'm actually surprised the latter two cache at all since they aren't physical files. I'm assuming Details and Edit don't cache because they don't work without querystring parameters.
Is it POSSIBLE to cache these two views at all? Or does anyone know of anything on NuGet that addresses this situation?
I changed this in the GET method for my Edit action to return an empty Model if there was no ID
if (id == null)
{
//return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View();
}
This allowed me to load the Edit page without a querystring variable and not get an error message. The page loads with no data but it allows me to cache it. At this point I suppose I would have to tell my service worker to check if the page is online. If it is, route the request normally, else query the local storage and manually plug the values into the fields.
So let this be a lesson to anyone creating Offline-enabled apps with MVC and using Cache API. Get rid of the lines that return bad request errors in your CRUD views if ID numbers aren't passed. Just pass back a blank model to the view (return View()). This allows you to cache your pages. And you'll obviously need to write code to handle the offline retrieval and presentation in code that executes when the page loads, but it will still allow you to utilize the MVC/Razor features when online.
One thing to note: "/App/Edit" will cache. If you load "/App/Edit/2", it won't match a url in your cache so you'll get an offline message. However, you can easily modify your Index page to send the ID via post. Just have a form on the page that goes to the Edit action and change the link to an underlined span with an onclick that sets the value of a hidden field to the ID. You'll have to pass another hidden field to let it know that it needs to retrieve instead of update (since the controller has different GET AND POST actions for Edit. The GET action is useless, but keep it for caching. You're retrieval that you normall would do int the GET is now going to be done in the POST with an if statement to check for your hidden field flag.

Express routing same path to either NodeJS API code or AngularJS frontend

I have the following things I want to accomplish. In the end I feel it is just a simple thing but I can't get my mind wrapped around it architecture-wise.
I have a simple NodeJS Express server that serves an AngularJS frontend via
this.app.use(
express.static(__dirname + '/' + settings.env)
);
Now I have some API Endpoints that are supposed to be at least of RESTful path-naming. I have AJAX Calls to them on some button clicks on the Front-End.
Let's say one Button is to load and view a list of "Loans"(Whatever this might be): GET /loans.
The Angular frontend reacts on and writes links like this: /#/loans
That was Question Part 1: Why is this? And more importantly: Is it common practice to keep it like that?
Now I am also sending out e-mails that have Buttons in them that the receiver can click.
Right now I cannot remind anymore why I wanted this, but it made sense when I decided to.
I want to be able to request GET /loans as path on that button click in the e-mail and have the Express routing decide whether to run logic and return a json or to "reroute" to angular to render the page.
That was Question Part 2: Is this something I should or should not want to accomplish? And if I still want to accomplish it what would be the best way?
I'll have another shot on the 2nd Part in Short:
I want to decide depending on the Accept-Header whether to return a json or to "reroute" to static files.

How can I send back one preset field of data in an HTML form?

I am working on a Node.js website. It maintains data about districts in a province. To edit district data, the admin types the district's name and the year and goes to a form (/edit?district=blah&year=2010) that has various fields about the district. How should I track which district and year the form was filled out for in the POST route's scope?
Basically I want to send back data in the current URL's parameters with a form POST.
Require body-parser module in your node server.. Then u can get the parameters posted in the body like request.body.paramName in any of your routes with post method.
I added ?district=blah&year=2014 dynamically to the action field of my form and it works! I can get the two variables using req.query.district and req.query.year in the POST handler. Another way that people suggested to me was to have hidden input boxes on the page with the data pre-filled (using JS or any templating system you're using) and have it submit with the form.

Categories

Resources