Passing JavaScript data to page, best practices? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a web application where I need to pass some user data to the JS application on page load. I've identified 3 different approaches, and am wondering what is the best practice with regards to this. The data is not particularly sensitive, but it would be best it is somewhat more secure compare to others.
1. Asynchronously load the data
Using something like $.ajax(). I don't like this approach because it usually leads to the whole "loading" phenomenon and I would like to avoid. Have the data ready than make a separate call.
2. Burn the data into the page.
This can be achieved by doing something like this
<script>
var userdata = { somekey: somevalue }
</script>
3. Make a request using script tags
This can be achieved by doing something like this
<script src="server/getdata"></script>
I understand that this is somewhat like the 1st approach since it makes another get request to the server.
My question is, is any of the 3 approaches above different, or better in terms of security. I understand that all 3 methods are not particularly secure, especially since it can be easily sniffed either way, but is any of the above method a better practice than the other 2, and why?

Of the ones you've given, 2 is best, for just the reasons you said. However, I would not add a new global for it. Rather, I would do:
<script type="text/javascript" src="application.js"></script>
to create someGlobal (among other things) then:
<script>
someGlobal.userdata = { somekey: somevalue }
</script>
Another couple methods with the same advantages are:
data attributes. These are the data- ones. You can put arbitrary data, associated with particular elements (sometimes particular elements make sense; otherwise, you can use body).
Hidden form fields.

Related

What's the added value of using Observable over normal Array? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've been using Observables in Angular in the state layer to store the app data and to share that data among the components of the app. With a belief, using observables, that data would passively update itself in the template whenever it changes, without checking it manually.
So out of curiosity, I've made the following demonstration to see the result of not using Observables: stackblitz
It turns out that the template passively updates itself by using a normal array instead of using observables.
I'm wondering, what's the added value of using observable instead of a normal array to store/share data in the angular app?
Use RxJS Observables when
Composing multiple events together
Adding Delay
Clientside rate limiting
Coordinating async tasks
When cancellation required (although you can use abortController for modern Promises)
they're not good for
simple button clicks
basic forms use
Hello world apps
UPD: RxJS shines when you need fine-grained control over the stream of events (adding delays, or using operators like debounceTime/ThrottleTime, etc.). If you only intent to apply some changes per event (without having control over the stream itself), then reactive approach probably not the best option.
Although I feel obligated to state that you can implement the same logic (~control over stream) without reactive approach, but it would be much more error-prone and not easily scalable).
In your particular hello-world app reactive approach isn't the best option (IMHO). If you want to see the power of RxJS by your own eyes, you may try to write an app with search field, where the app should wait some time before sending actual request (limiting the amount of request: they shouldn't be made for every new letter, look debounceTime for reference) and also requests shouldn't be made for the same inputs (users typed something, then changed theirs mind and returned to previous input, and all of it within the range of, suppose, 600ms. Look distinctUntilChanges).
You'll see that the non-rxjs alternative is much more verbose and difficult to read (and, more importantly, scale).

Is it ok to create global URL variables? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a number of scripts that I need to pass a url parameter to. I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.
What I want to do is store the url within a global variable so that I have to change the url in 1 place to feed the various scripts downstream that rely on it.
I thought about a simple globals file that contains, for example:
var myURL = 'http://www.google.com'
I'll have additional urls, but I plan to follow in kind with those.
I've heard that this is not good practice, but what's the alternative given what I'm trying to do?
If you really have to have some global configuration, I'd stick it in an object / class so you could restrict your use of global variables to the minimum necessary, e.g.:
var Config = {
googleUrl: 'https://google.com',
otherUrl: 'http://example.com',
};
That would be better than having a global variable for each thing.
I've heard that this is not good practice, but what's the alternative given what I'm trying to do?
It might be worth explaining your use case a little more. For instance is it appropriate for these URLs to live in JavaScript configuration or do they belong to a specific UI component? If so should the UI component specify the URL on a HTML element as a data-attribute? If they belong with a specific JS module, should they be local variables for that module?
I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.
Could you not use window.location.hostname for those?
I might be wrong, but I don't know why this should be a problem, as long as you are using constants.
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
Edit:
But at the end you should avoid using global variables, because they could cause some problems at later debugging.

Too many short PHP files [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I searched a bit around before realizing I need some more info on this. I have an interactive website using ajax calls to get info from server. The (authenticated) user will click around quite a bit to manipulate this data, and it will be continously uploaded to server. The thing I'm not sure about is how to do this in the best possible manner, so that my project is scalable if necessary in the future.
To give an example. User logs in and a list view is filled up with data from server. If the user double clicks one of the elements in the list view, he can change the name, and the change should be uploaded to the server immediately. What I've done now is make a file called "changeName.php" which gets called. If the user clicks something else, let's say there are ten different buttons that each changes a particular setting. How would I go about uploading all of these different data changes without having ten different php-files all doing there own little thing? I hope I explained things well enough, but if something is confusing, I'll try my best at clarifying.
Rather than POST the changes to one PHP file, you can pass the request to a single php file that handles multiple operations. Include the type of request in the POST data itself. Then for instance that file can use a switch statement on that key to determine which operation to perform, and then call a particular function in the file to process the data.
if ( isset( $_POST['_action'] ) ) {
switch ( $_POST['_action'] ) {
'delete':
deleteRow();
break;
'update':
updateRow();
break;
'default':
foo();
}
}
// Functions omitted
Note that as others have said, using a proper MVC framework will make this much easier for you and will have other benefits (security, extensibility, etc). In particular, you can have a framework to take care of routing requests for you.
In a small or prototype project where you don't want to rely on a framework, using a method like the switch statement above can at least get you started.
The best way to keep this organised is to use a proper framework. Laravel is a great option for this and will help keep your code well organised and maintainable.

Should numbers be avoided in Javascript function names? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I heard from a JS developer recently that you should avoid using numbers inside function names.
For example:
function test1test() {
// function body
}
I've never come across this before so I was wondering if it's true? If so, why?
There's nothing wrong with having numbers in your function name, it's just a little unconventional. The ultimate goal in function and variable naming is readability and clarity of code, so if you think including a number in your function name make the code more clear, you should make that a priority.
However, for maximum readibility and clarity in most cases, your function names should be camelCase verb phrases to follow the predominant convention.
For instance, you might want to name a function convertToMp3(), in which case it would be silly to instead name the function convertToMpThree(). But you should avoid using names like obj2Array() or format2(), because those don't make your code more clear.
Ok, I'm going to try to answer this in without a my-opinion base...
Refering to W3's article on Javascript's best practices, we find the following statement, regarding to names:
good variable and function names should be easy to understand and tell you what is going on — not more and not less. One trap to avoid is marrying values and functionality in names. A function called isLegalDrinkingAge() makes more sense than isOverEighteen() as the legal drinking age varies from country to country, and there are other things than drinking to consider that are limited by age.
Note the not more and not less. There's no reference on why it should matter to use or not a number in the naming of a function/variable. It is just a case of what will be easily understood when you/others read the code.
doesnt make sense to avoid this in general..
its rather a question of style and when it actually makes sence in your context
The only actual restriction is that you cannot start a member name with a number. Other than that, it's a matter of style. Having said that, I cannot think of a member in the standard library that has a number in it. It's certainly rare to need this, but it can be useful. No need to be too dogmatic about these kinds of things.

Organizing large javascript files [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've started to accumulate quite a few lines of Javascript code for a website. Everything has been in one file so far and that file is becoming impossible to maintain. If there is an error in one line, the entire file breaks.
I've tried splitting the code up into multiple files but there are some shared methods across objects like: validateEmail(address).
Right now, I have my code organized into objects, like so:
var ProductPage = {
addToCartBtn: "#add-to-cart",
init: function() {
ProductPage.initAddToCartPopup();
ProductPage.initSidebar();
...
},
...
};
Then, I call ProductPage.init() on $(document).ready.
My issue is: when splitting ProductPage into a separate file as ContactPage, for example I cannot access ContactPage.validateEmail(). I believe this is because my code is wrapped in jQuery's:
(function ($) {
...
})(jQuery);
Does anyone have insight on how they have organized large systems of Javascript? Also, I plan on doing optimization with putting all of this into one file and compressing it. So, any method which will benefit both maintainability and ease of optimization would be awesome.
validateEmail like methods are functional in my opinion. By functional I mean, y = f(x). These functions are not changing the state but returning an output which are being computed on the passed input.
You might want to keep all this utility functional methods in a separate module and tag it to a global namespace. Make sure to load this(these) utility module(s) before utilizing them.
You can use require.js for dependency management.

Categories