Dump state into json or tsv (backend) - javascript

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)

Related

What is the best way to manipulate an API AJAX JSON response and pass it to another page?

I think I have a tough one for you guys. Or at least it's been tough for me. I've been searching for the best way to do this in Stack Overflow and everyone that has asked has been given a different response.
I have this code that is accessing an API and calling a maintenance list of all the vehicles in a fleet.
function getMaintenanceList() {
var settings = {
"url": "API URL HERE",
"method": "GET",
"timeout": 0,
"headers": {
"Authorization": "Bearer token here"
},
};
$.ajax(settings).done(function (response) {
// The response the API sends is a JSON object.
// It is an array.
var jsonMaintenance = response;
var parsedJson = JSON.stringify(jsonMaintenance);
//Left over code from when I was trying to
//pass the data directly into the other page
// I was unable to do so
//return jsonMaintenance;
//Left over code from when this was in a PHP file
//and I was posting the stringified response to the page
// for testing purpose
//I had to disable CORS in Google Chrome to test the response out
//console.log(jsonMaintenance);
//document.getElementById("main").innerHTML = parsedJson;
});
};
The code above works well. What I was attempting to do here was write the stringified response to a file. Save that file in the server. Call it from another page using JavaScript and save it as an object in JavaScript, parse it using JSON.parse(), and then pull the required information.
Here's an explanation as to why I'm trying to do it this way. When I call the maintenance list from the API, I'm getting the entire maintenance list from the API, but I need to be able to display only parts of the information from the list.
On one page, we'll call it vehicle-list.php, on it I have a list of all the vehicles in our fleet. They all have unit numbers assigned to them. When I click on a unit number on this page it'll take me to another page which has more information on the vehicle such as the VIN number, license plate, etc. we'll call this page vehicle-info.php. We're using this page for all the vehicles' information, in other words, when we click on different unit numbers on vehicle-list.php it'll always take us to vehicle-info.php. We're only updating the DOM when we go to the page.
I only want to include the information specific to each vehicle unit in the page along with the other info in the DOM. And I only want to call the info from the API once as I am limited to a certain amount of calls for that API. This is why I am attempting to do it this way.
I will say that what I originally wanted to do was get this JSON response once every 24 hours by using a function in vehicle-list.php save the reponse as a variable as seen above var jsonMaintenance = response; and then just access certain parts of the array every time a unit number is clicked. However, I have been unable to access the variable in any other page. I've written many test files attempting to call jsonMaintenance without success so I've been trying to to just save it as a text file to the server and I haven't been able to figure that out either.
After explaining all of the above. My questions are these:
How do I best manipulate this data to accomplish what I want to accomplish? What would be the best standard? Is the above code even the right way to call the data for what I'm trying to do?
There doesn't seem to be a set standard on accomplishing any of this when I search on Stack Overflow. I'd like to be as efficient as possible.
Thank you for your time.
there is a lot of ways how you pass your data through your website after getting it in from an api call, the best approach is to store these information in a database and call it back in which ever way you want, you can do that as far as you are using php, you can store it to sql or to access, if you don't want to store these information in a database like in sql or access, then best way is to store it to localStorage and call it back whenever you want.
I will show you briefly how you can do that, if you want better explanation post an example of your returned data.
to store an item in localstorage use,
localStorage.setItem('key', 'value');
to call an item back from localstorage use,
var somevar = localStorage.getItem('key')
to remove specific item from localstorage use,
localStorage.removeItem('key')
to clear all items saved to localstorage use,
localStorage.clear()
be aware storing the data to localStorage is only at the station you are using
I would do it somehow like this.
Call the maintenance list from the API with the server side language of your choice which seems to be PHP in your case. Lets say the script is called: get-list.php. This can be triggered by a cron job running get-list.php in intervals limited to the certain amount of calls that you are allowed to do for that API. Or if you are not able to create cron jobs then trigger the same get-list.php with an AJAX-call (eg jQuery.get('sld.tld/get-list.php') - in this case get-list.php have to figure out if its the right time to call the API or not).
Now that you have the data you can prepare it as you want and store it as a JSON-string in a text file or database of your choice. If I get you right you have a specific dataset for each vehicle, which have to be identified by an id (you named it "unit number") so your JSON would look kind of: {"unit1": { property1: "val1", property2: "val2" }, "unit2": { property1: "valXYZ", property2: "valABC" }} or alike.
Now when you link to vehicle-info.php from vehicle-list.php, you do it like so: ancor or similar as well. Of course you can also grab the data with AJAX, its just important to deliver vehicle-info.php the corresponding unit number (or id - better to say) and you are good to go.
vehicle-info.php now have all there is to render the page, which is the complete data set stored in text file or data base and the id (unit number) to know which part of the whole dataset to extract.
I wanted to give you this different approach because in my experience this should work out just so much better. If you are working server side (eg PHP) you have write permissions which is not the case for JavaScript-client side. And also performance is not so much of an issue. For instance its not an issue if you have heavy manipulating on the data set at the get-list.php-level. It can run for minutes and once its done it stores the ready-to-use-data making it staticly available without any further impact on performance.
Hope it helps!
If i ran into a similiar problem i would just store the data in a database of my own and call it from there, considering you are only (willing/abe/allowed) to request the data from the API very rarely but need to operate on the data quite frequently (whenever someone clicks on a specific vehice on your applicaiton) this seems like the best course of action.
So rather than querying the data on client side, I'd call it from server, store it on server and and have the client operate on that data.

Front-end instant record creation and deletion without waiting for back-end to return

For a to-do list app, when the user creates a task, the back-end would need to return an ID to identify the task uniquely so that when the user deletes the task later on, the correct task can be referenced in the back-end.
But what if the user deletes the task before the back-end returns with the identifier?
Possible inelegant solutions i thought of:
prevent the user from deleting task until back-end returns the identifier
generate the identifier on the client side (perhaps with the user id + timestamp)
couple the creation and deletion actions together, assigning a temporary id on client side and using Promises to ensure correct deletion. (ugly solution for a Redux framework?)
A "clean" solution which could work well with Redux could be using a generated identifier on the client side.
So an user, create a task id is generated on the client and after is sent using AJAX.
I would recommend disabling the delete button until you get a response back from the server. I know there are more examples out there, but one example of this that I can think of is in the TFS portal. When you create a new User Story, the row gets added to the grid (at the top) immediately. And the api POST is sent to the server. And if you right-click that row immediately, you get a popup menu with a spinner. Then, after a second or so, the front-end gets the response back from the POST, and the popup menu is populated with two items (Add Task and Add Bug).

Using AJAX and jQuery to store data

I am looking for a way to use AJAX and jQuery to store data from one form in another without losing the values. I want to be able to keep this data away from the front end user and allow them to remove the information should they wish to. I need to be able to get this information out when the user submits the data. I would like to be able to store the values in an associative PHP array if possible, for example:
<?php
$information = array(
"first_information"=>array(
"name"=>"Sam Swift",
"age"=>21
),
"second_information"=>array(
"name"=>"Example Name",
"age"=>31
)
);
?>
I would have used a database for this but because of volume this will not be possible. I want to keep the data away from the user so that they have no access to it at all, the data should be held where the user has no way to see it, access it or change it. This is due to the nature of the data and all of it should be as secure as possible.
Any information that you store client-side is naturally going to be accessible and mutable by the client. If this sensitive data is data that the user is entering, then you really shouldn't worry about them manipulating the data (because that is what they are supposed to be doing). If however it is data that is being sent by the server - and never displayed or used in that form by the client - this is data that should never leave the server in the first place.
Ajax is not specifically a solution to this problem - whether you send the data asynchronously (i.e., piecemeal with Ajax) or as a full HTTP post is immaterial. You need to store the sensitive data on the server only along with a session ID to associate it with the client session.
Without knowing exactly what data you are storing nor what you are doing with it, it is difficult to advise you how to proceed. You should rethink how you are structuring your application if you are sending sensitive data for the client to work with. The client should only ever see the input and the results. The processing should be done on the server.
For example: perhaps your user is adding an amount to a bank balance. The user enters the amount on the client. but you don't want the client to see or be able to modify the actual value. You could send the balance to the client, perform the addition operation, then send the total back to the server. Far better would be for the client to send the amount to add to the server, which would then add the value to the balance, and return a confirmation for the client to display.

How can i use REST in python django for multiple tasks

This is the first time i am using REST for any web applications.
For normal get an post and i simply call the API done in Django Rest Framework.
But i am not able to think how can i deal with situations where something more needs to be done.
Suppose I have
List of users in database and their product they have bought.
Now i have web form where if someone adds the user and then submit the button , then
I have to get the list of items bought by that user in 5 hour window
Update the row in database which says buy_succeessful to false
Then again get the list of orders from the items he has bought and then update the rows with order_successful to false
Now current in my submit actions i am doing like
call to api to add the user in override manual enrty table. This is simple post to that table
Then after getting the sucessful tehn i again call api to list of items this user has bought using Query parameters . Then i have the list
Then again i loop through the list and post to api for updating that record in datbase
and so on
I am feeling this is not right.
I have found that quite often there are some more things to do tahn just saving individual objects in database.
whats the best way to do that. DO i need to have view api for every function
Try the 3rd step of the DRF Tutorial:
http://www.django-rest-framework.org/tutorial/3-class-based-views
Here, it shows how to do a "PUT" request for updating data. And also some of the other DRF features.
Also, you can reference serializer.object which is the object instance of the django model record that you are saving to the database. This question here talks about adding extra attributes, etc... before saving to the database:
Editing django-rest-framework serializer object before save
You can also access the record post_save and there are other hooks in the framework that you can use.

ajax and local/session storage pattern

I'm building a web app that uses ajax to communicate with the server. Basically, the user requests a record, it comes back in json, it's added to the DOM and the user makes changes to it. When the user requests the next record, the current record is stringified and sent back to the server and the following record comes back.
All this works really well.... as long as the user keeps requesting records. However, I am wondering how to handle the situation where the user stops his work: how do I get the last record updated?
I thought of adding the working record to the local storage while he's editing it and at each edit, updating the local storage and if he logs on next time and there's still a record in there, ajax it when he logs on. The problem with his approach is that if another user logs on to the same computer, then when that new user logs on, he's updating the data of another user.
I thought of using the window.unload event also; but that doesn't solve the problem of the user closing his browser before the final update.
What are some good ways to handle this issue. Thanks for your suggestions.
I would consider a 'draft-like' feature. Where you could upload changes after a certain amount of time of no input, for instance, after 15 seconds of no input, push those changes.
If your app requires login, you could key the localStorage using their ids like so:
localStorage.getItem( "user13434" )
would retrieve data for user13434
localStorage.getItem( "user12345" )
would retrieve data for user12345
If the information is sensitive but not too sensitive you could add encryption, but it can be decrypted by experienced users which is why it must not be too sensitive.

Categories

Resources