Implement repeating behaviors with numerous amount but same html elements - javascript

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'))

Related

Passing additional information per input box using HTML

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.

Save Value State for Public Sharing (Add to URL)

http://liveweave.com/xfOKga
I'm trying to figure out how to save code similar to Liveweave.
Basically whatever you code you click the save button and it generates a hash after the url. When you go to this url you can see the saved code. (I been trying to learn this, I just keep having trouble finding the right sources. My search results end up with references completely unrelated to what I'm looking for, example )
I spent the past two days researching into this and I've gotten no where.
Can anyone can help direct me to a tutorial or article that explains this type of save event thoroughly?
To understand the functionality, it is best to try and identify everything that is happening. Dissect this feature according to the technology that would typically be used for each distinguishable component. That dissected overview will then make it easier to see how the underlying technologies work together. I suspect you may lack the experience or nomenclature to see at a glance how a site like liveweave works or how to search for the individual pieces, so I will break it down for you. It will be up to you to research the individual components that I will name. Knowing this, here are the keys you need to research:
Note that without being the actual developer of liveweave, knowing all the backend technology is not possible, but intelligent guesses will suffice. The practice is all the same. This is a cursory breakdown.
1) A marked up page, with HTML, CSS, and JavaScript. This is the user-facing part of the application, where content can be typed, and how the user interacts with the application.
2) JavaScript to asynchronously (AJAX) submit the page's form to the backend for processing.
3) A backend programming/scripting language to process the incoming form. In the case of liveweave, the form is POSTed. It is also using PHP to process the form.
4) A database table with a column for each language (liveweave has HTML, CSS, and JavaScript). This database will insert the current data from each textarea submitted in the form and processed by PHP as a new row. Each row will generate a new hash and store it alongside the data just inserted. A popular database is MySQL.
5) When the database insert is complete, the scripting language takes over again, and send its response back to the marked up page (1). That page is waiting for a response from the backend. JavaScript handles the response. In the case of liveweave, the response is the latest hash to be used in the URL.
6) The URL magic happens with JavaScript. You want to look up JavaScript's latest History API, where methods like pushState will be used to update the URL in the browser without actually refreshing the page.
When a URL with a given hash is navigated to, the scripting language processes the request, grabs the hash, searches for the hash in the database table, finds a matching row, and populates the page's textareas with the data just found.
Throughout all this, there should be checks to avoid duplication and a multitude of exploits. This is also up to you to research.
It should be noted that currently there are two comments for your question. Darren's link will indeed allow the URL to change, but it is a redirect, and not what you want. ksealey's answer is not wrong; that is one way of doing it, but it is not the most robust or scalable, and would not be the recommended approach for solving this.

best way to relate a variable and its ID

I am getting results from a database with a simple php while loop, one of the pieces of information is a number that links to another table where the value is stored, I can think of plenty of ways to get this information linked and display the text related to the value but I want to know the fastest way to do it as I have a huge set of results so every bit of speed will make a difference. Is an array fastest, javascript? any advice you can give me would be great.
The schema would look something like this
col_table
colID(autonumber) colName(str) colState(int) colDate(date)
state_table
stateID(int) stateType(str)
I want to select the correct state type based on the colState matching a stateID and output the stateType while preserving the stateID for so I can edit the field and update the database using the number.
Using MySQL will be faster.
If you have to get through a PHP loop to read your results and make each time a new MySQL request, your script will take longer.
You can increase speed on MySQL by creating the right kind/amount of index, choosing wisely what is store in each field.
The later you parse content, the longer it will take. If you go for js, you will have to read a DB, loop trough it in PHP and do it again in JS, and making more request again ...
A join can be a good solution. A view can be even more easier to treat. Yuo can also consider caching results
Use a timer in php and try trial and error method. Use the time returned by the timer to evaluate speed and efficiency.
you should prepare your data on server side it is faster.
Whether you choose your server or database with a fast query it depends. If you have complex object graphs then the processing of results from db in order to create associations would be time consuming so an ORM is the way to go, otherwise as is your case with a simple join i would simply retrieve all data from db.
If you use php for rendering as well then render it using php no js.
If you use js for your ui then prepare data on server side and publish it via a REST webservice in json,i.e. usind json_encode functions of php, then retrieve it from js and output.

Is it more efficient to let ajax get the html or get JSON and make the javascript create the html

The title says it all, but basically I use ajax to get information and I don't know if I should have PHP create the HTML which then gets returned to the client and then javascript just plugs it in or if I should have the server just send all the information through JSON and have javascript (jQuery) create all the html that holds it.
Which one is more efficient?
Thanks
I would say it is better practice to serve only the JSON data. Why?
Well, perhaps, you want to hook up a different type of client to your data service.
Maybe you create a mobile app, and it needs the same data, but wants to display it differently.
If you are providing the HTML markup as well, then now your mobile app has to parse the data it wants out of the HTML structure, rather than just dealing with the data right away.
On an efficiency scale, that depends on what you consider efficient.
For example, it would be efficient from a bandwidth perspective to only send the JSON. However, it would be more efficient from a processing standpoint on the target client to simply give it an HTML string to display.
If you are considering ever having different clients accessing the same data, though, then you want to create a single data interface that serves JSON (in your case), and allow the client to decide how to present that data.
Separation of concerns.

HTML as a result for an AJAX call (PROs an CONs)

What is your opinion (PRO an CONS) about returning HTML code as a result for an AJAX call. It is, if the app creates a new item in a list and it needs some extra parameters or some pattern customization, instead of modify it through JS, we can send it templatized through an AJAX call.
The point is that HTML snippets are sent from the server to the client computer and integrated in the document DOM. Any problem with this approach?
No problem with it at all, perfectly normal and reasonable thing to do.
There is sometimes a use-case for sending data rather than markup and expanding it with client-side templating, but that's mostly for situations where you're sending a lot of data and so want to keep the size on the wire down. (E.g., a large table where the HTML representation of it is 100k but the raw data in, say, JSON format would only be 10k.) Or when the templating varies depending on client-side conditions. But by and large, perfectly fine to send HTML you then incorporate into the DOM via innerHTML (or any of several libraries' wrappers for it that help you with the odd niggle).
This is a common approach.
If you're adding items to a list or replacing the contents of a pod with something completely different this is fine.
This also makes it easier to apply AJAX to existing sites (for example overlays or something) because you can make requests to existing pages and then strip out the bits you don't want.
However, it would be better for updates where only a value is changing then you should perhaps use Json there.
Personally, I almost always choose to receive a JSON response with no markup or formatting applied, but that's just because I like having a really flexible, granular response so I can do whatever I want with the returned data, without having to possibly strip it out of HTML. This is NOT necessarily the easiest or most elegant solution in a lot of cases! :)

Categories

Resources