Passing additional information per input box using HTML - javascript

I'm asking this question since I'm simply not clear on where to research further - I have experience primarily with Python, while my HTML and Javascript knowledge are on an as-needed basis. I simply haven't been able to figure out the most elegant and standard way to do this, and which component (the HTML itself, a Javascript component, Django) should be responsible for doing what I want.
I am trying to create a form for input of linguistic data with a Django app. Important for what I'm doing here is that each datum has associated tags. Also, most linguistic data is paradigmatic, so I want to be able to have users input an entire paradigm at a time (rather than one single datum at a time, which can be done already using the Django admin interface). I also, ultimately, want to have the paradigmatic input be dynamic in the future, so that I do not have to hardcode things.
For example, I would like have a form that looks like the following:
On submit, I would like the page to send something like this to the server:
'I', tags:'singular, 1st'
'we', tags:'plural, 1st'
ˈYou',tags:'singular, 2nd,masculine'
...
I simply don't know what the best way is to embed this extra data into the website so that it gets submitted when the page gets submitted. Ideally, the input boxes could somehow 'inherit' the tags based on their position in the columns and rows rather than each input box needing to be have that information added individually.
The only idea I've had so far is to embed the tag information into the names of the input boxes so that the string passed on a get command would be something like '?singular_1st=I&plural_1st=we&singular_2nd_masculine=You' and I would just have to process the strings on the Django backend. I could also use javascript to assign the names of each of the textboxes on pageload somehow, though I'm not sure how to figure out which textbox is located where relative to the headers of the table.
What is the best way to do this? Can I somehow pass more structured data on submitting the page, rather than having to reparse everything on the backend? I've read something about passing JSON to the server, but I'm not sure how exactly to do this. Similarly, there's a data attribute in HTML 5, but I'm not sure how (or if) that gets passed to the server on submitting a page. I'm not asking for anyone to do my coding for me, but simply a suggestion about how best to do this and further resources or tutorials showing similar projects.

Related

How frequently data should be saved if form is very large

I have a doubt on saving data in database using ajax. (I can do this part). My problem is I have a very large form which is nested( I can't change it). Large form in terms of input fields which need to be saved in data approx 100 fields. new field may open it depends on users selected options.
ex- suppose one question is like which game you play. In multi select drop down if he selects one game than next questions would be how frequently you play this game .on which day which time and many more. Each game may have different set of question.
Now my problem is how to save this data in database. Should I save it after user click submit or should I save it in between user is feeling data. so that he refresh the data it can have his data filled .
How frequently should I send Ajax request for saving data and how to get the data from the fields which are newly field and how I should save it in Rails.
I know about update.attributes
please help me or give some suggestions how should I do it.
If you live edit or only on save has mostly user expierence questions.
But if you are frequently saving (like an autosave) and are worried about the size (100 normal columns might be OK anyway, allthough large text or blobs less so) then what you want to do fairly simply is only save the fields that have actually changed.
There are many ways to implement this in JavaScript. You might just save each input when the user finishes editing it (e.g. the input loosing focus) or you might save based on a timer and track the changed fields since last save.
Then have your JavaScript just include those fields in its AJAX request (PATCH migh be a good method to use). Rails should then only try to save the attributes on the object that you changed (via update_attributes, or save on the ActiveRecord). If you want to also optimise out the SELECT, use update or update_all on the class. e.g. ends up like:
MyBigRecord.update(id, title: "My new title")
You can easily use the normal strong parameters here, which only includes those actually present in params.
MyBigRecord.update(id, params.require(:my_big_record).permit(:title, :author, :etc))
If you need to deal with sub objects then you may need some special handling, but the idea is the same). A little bit of logic can also do the initial create on demand, allthough your JavaScript then recieve the id to use for future saves.

Implement repeating behaviors with numerous amount but same html elements

Let's say we have a group of HTML element like this JS fiddle with certain behaviors. Having one of this is easy on a HTML page.
But what is the best practice of having 1000 of them (the same JS fiddle) on a page? This is not only about dynamically generating required HTML elements but more importantly generating the behaviors/JS codes for each individual element (with different values and id).
An Example:
document.getElementById("ID1").onchange = function () {
//some complicated behaviors
};
Generate the a ID2/ID3/ID4...ID1000 version of the above codes in run time when needed. Note that it must be running on HTML environment with no servers. Select options/data are stored in the same html file (as an array or some sort).
Any advice or suggestions are appreciated.
Ideally, rather than loading up all the possible options in the DOM, you would use AJAX to fetch the next set of options from the server. So when you select the state, it goes and grabs the counties for that state, then when you select the county, it goes and grabs the cities for that state.
To go further, when you select the state, it sends the selected state back to the server to fetch all the counties for that state. Then when you select the county, it sends that back to the server so it can fetch the cities.
You can use the server side language of your choice of course (PHP, ASP.net, Ruby, Python, etc.)
Otherwise, you're injecting a ton of data in to your DOM that will never get used and that would vastly increase load times; whereas AJAX is generally pretty fast.
There are lots of tutorials regarding the use of AJAX so I'm not going to cover that in the answer, but that is your best solution.
You tagged the questions only with Javascript so I assume that you have the data locally and you don't retrieve it from a server.If you take the data from the server use Ajax and get only the data that you need at that moment.
With Javascript you can use
document.createElement('element'); // this is faster than Jquery if you generate a lot of data
with Jquery you can use
$(document.createElement('element'))

I need access to variables both in php and the page's javascript

I am working on a php/JavaScript web application that must perform many calculations using many values input by the user. There are several pages of inputs, and calculations using values input on previous pages are everywhere.
I have been passing the recently entered values between pages using $_POST, and storing them for use in a serialized class saved as a $_SESSION variable. One obvious way to pass values from PHP to the page for use by JavaScript is to populate the page with hidden form elements. JavaScript could use this data and modify it as necessary, then pass the values via POST.
I may have many such hidden elements, and I can't help but think that this is a good way to slow down the pages. Is there a better way to store this data between pages? Cookies?
Thanks!
SH
Search AJAX in google. It's a technic that helps your javascript to communicate with your php. First it is hard to learn the syntax but watching videos from youtube will do just fine.

How to save information as variables with html5

I'm making a simple point and click stock simulator for school using html 5. I have a form set up, and they click submit to send the information. Is there a way to call that variable forward and to have it appear in it's current form. Math will be behind it. For instance, if they submit 3, it could fluctuate to different numbers, is there a way to display the fluctuation real time?
The form inputs are posted to the web server and handled there. you need to familiarize yourself with that concept first.
Eg.
asp.net:
Request.QueryString["key"];
php
$_POST["key"];
Google these and see how you get on. Good luck!
I would recommend checking out KnockoutJS. Using data-bind on the HTML elements, you can construct a viewmodel in javascript that would hold these values, and update them in real time.
http://www.knockoutjs.com for knockout itself, and http://learn.knockoutjs.com for some really good tutorials (and if those don't work out for you, there's always SO).

Is it bad to store temporary data into hidden element? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
At one interview, once I attended, I was asked to create one java script based functionality in which I was said to create one form (say i.e first name, last name, email, age) and one listing(actually listing was kind of another form storing multiple entries) below this form. On submitting this form one new row was added to listing. However it is possible to remove any previously added listing row. and after adding removing, finally need to store this final state of listing. ( Kind of form post and server side scripting comes into picture )
So what I did that, On Form submit, adding a new <tr> row in listing table at the same time I serialized all form data except submit button using jQuery serialize and stored it in one hidden element of listing form.
On removing listing row, I was removing <tr> row along with respective hidden element for the same row.
All was working like great without any error. But the interviewer asked me that "The approach I used (hidden elements) was really proper?".
I replied, I could have used json?
but Could not crack interview.
So I want to know what is best approach that We can use to store data in such conditions?
Another approach for client-side is to keep a list of objects separately and only store the reference to each item inside a property of your DOM element. This approach is very similar to what jQuery's $.fn.data() provides and has these advantages:
You don't have to serialize anything, the data stays in its native format; it should be said that you could have achieved this by adding a property as well.
All your data is kept in one place instead of scattered around in the DOM.
This is an example implementation:
(function(ns) {
var entries = {},
entryId = 1;
ns.Entries = {
addEntry: function(data) {
entries[entryId] = data;
return entryId++;
},
getEntryById: function(id) {
return entries[id] || null;
}
};
}(this));
Calling Entries.addEntry returns an identifier that you can store in one of the DOM element's properties:
tr.entryId = Entries.addEntry(data);
Later you can use that entryId property to find the corresponding data in the entry list and use it.
var data = Entries.getEntryById(tr.entryId);
Demo
Of course, this particular functionality can also be solved server-side by using sessions.
Thanks to HTML5, we now have the ability to embed custom data attributes on all HTML elements. These new custom data attributes consist of two parts:
Attribute Name
The data attribute name must be at least one character long and must be prefixed with 'data-'. It should not contain any uppercase letters.
Attribute Value
The attribute value can be any string.
Using this syntax, we can add application data to our markup as shown below:
<ul id="vegetable-seeds">
<li data-spacing="10cm" data-sowing-time="March to June">Carrots</li>
<li data-spacing="30cm" data-sowing-time="February to March">Celery</li>
<li data-spacing="3cm" data-sowing-time="March to September">Radishes</li>
</ul>
We can now use this stored data in our site’s JavaScript to create a richer, more engaging user experience. Imagine that when a user clicks on a vegetable a new layer opens up in the browser displaying the additional seed spacing and sowing instructions. Thanks to the data- attributes we’ve added to our <li> elements, we can now display this information instantly without having to worry about making any Ajax calls and without having to make any server-side database queries.
source: HTML5 Doctor
There are other methods too I believe.
Actually instead of using hidden elements , you can add data to the html elements using jQuery. This is a better approach to make your data a little less obvious/direct to the users. Check the data() in jQuery.
Nothing wrong with storing data client-side if the user can be trusted with it and nothing terrible happens to your system when he messes with it.
Only problem I can see with using hidden fields (or cookies) is that they get sent with every request, which might waste bandwidth. Not sure if that applies to your case, probably not, because you say you just submit once when all is done.
The problem with solutions that 'just work' is that they are not abstract enough and therefore tend to cause problems in the future. Consider your example; should you decide to store the temporary data in Local Storage (to allow users close their browser and return to it later), you'd have to rewrite how you store your data. If you stored it in a variable, you'd be able to add 'Save to Local Storage' just as easily as 'Submit to server' or 'Pass to Any Other Function' functionality. Your 'hidden element' approach would have to be rewritten for any purpose except posting to service.
To start with, multiple forms on one page are wrong - it's data loss antipattern. The correct approach would be to place everything into one form. This way, it would work even without JS and you could use JS only to improve usability, not to provide basic functionality. This solution would degrade gracefully an it would be easy to debug and maintain.
Of course, saving the data in hidden field is a valid technique.
By writing submitted data into the form itself, and reading again from it, you've tied these two elements together - they are said to be tightly coupled.
What word happen if another requirement came through to displaye previously submitted data in the table also? Or to put the form on a separate page?
If you take a more MVC approach, you can separate out the logic for the various parts - reading, writing and sending data. For example, as you said, writing and reading from a JSON model. This would make each aspect more readily extensible in the future.
I will not answer your question directly but will focus on interview and method you chose.
I would say you chose wrong way and well known IT company you applied this solution for can have problems.
You chose the way to store everything on client's side, but you shouldn't! As your client can lose a lot of data this way, because imagine the case when your listing form will never be sent? User will just forget to hit send (never trust user!). Then you lose everything... whole progress of your work... and let's say you've already added 50 listing items...
Also adding items like this can easily make your session expired (no requests to the server) and no data will be saved, because user will have to log in again. And you will have to handle it as well, or you will lose everything!
Sorry for exclamation marks, but I think data is crucial (especially for your client) so do not ever offer solutions which can make client losing it somehow.
So:
It's not bad to store data in HTML elements, but you need to apply this solution very carefully.

Categories

Resources