Get rid of long require strings - javascript

In PHP, I used to do things like this :
<?php
use Vendor/Namespace/Bundle;
$bundle = new Bundle();
What interests me here is that, following the PSR-4 convention (or any other convention), we could automatically require a PHP file and use its content. Is there any ways to do this in Javascript, or how to do not use some ugly require('../../../../../../../mymodule.js'); ?

Set the $NODE_PATH variable to whichever location you want require to look into by default.
http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
For e.g. setting it to /user/project/lib; you can do a require('mymodule.js') from, say /user/project/test/test.js, it'll work.

Related

Remove last 3 letters of div (hidde also in browser page source)

this is my HTML
<div id="remove">Username</div>
and this is my JS code
function slice() {
var t = document.getElementById("remove");
t.textContent = t.textContent.slice(0, -3);
}
slice();
Username load from foreach
{foreach from=$last_user item=s}
{$s.date}
{$s.username}
{/foreach}
This code working and remove 3 letter but when right click on browser and look at page sources i can see "Username" !
I need remove three letter because of privacy and security .
something like
*** name or usern ***
Thank for help me !
The only secure way to make sure the client can't see a particular piece of information is to never send it to the client in the first place. Otherwise, there will always be a way for the client to examine the raw payloads of the network requests and figure out the information they aren't supposed to know.
You'll need to fix this on your backend - either hard-code in
<div id="remove">Usern</div>
or, for a more dynamic approach, use a template engine (or whatever's generating the HTML) and look up how to change strings with it. For example, in EJS, if user is an object with a username property, you could do
<div id="remove"><%= user.username.slice(0, -3) %></div>
Changing the content only with client-side JavaScript will not be sufficient, if you wish to keep some things truly private.
With Smarty, you can define a modifier that takes a string and returns all but the last three characters of it.
function smarty_modifier_truncate_three($string)
{
return substr($string, 0, -3);
}
and then in your template, replace
{$s.username}
with
{$s.username|truncate_three}
If you want only the first three characters, it's easier because you can use the built-in truncate.
{$s.username|truncate:3}
JS doesn't change the source, it can only change the DOM, so what you can do is to keep the element empty and add a value to it using js, but don't forget that js runs on the client's side so its better here to send the string from the server without the last 3 characters.

Use one javascript script to dynamically modify another script

Yo!
I have an arbitrary javascript file, let's call it localScript, and just say it looks something like this:
<script id="myScript" type="text/javascript">
function () {
var blue = 'blue';
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"brown"
};
var bluePerson = function () {
person[color] = blue;
};
}
</script>
I want to be able to use another externalScript to dynamically change the contents of this localScript. For this simple example, let's just say I want to update some of the values in localScript, like—maybe change age of the person object to 75. (Obviously, there's very simple ways to do this, but for my use case it's imperative that I use another externalScript to generate the contents of this localScript).
It would be easy if there was something like .innerHtml which I could use in the externalScript which would allow me to select an element and then replace the 'innerHtml' contents. The localScript, though, obviously isn't composed of elements.
As far as I know, when using a script to modify another script, there aren't any 'easy' ways to reference variables/objects/items in the script.
Things I've considered are indexOf(), search(), and match(), which I could use in externalScript to find strings inside localScript and then replace the values. I feel though as these could be performance no-no's, especially if the script grows.
Are there any easy ways to do this—with an emphasis on performance? I feel like there must be some easy way to reference one of the items in the script, though, I suppose a script is all one large string.. and maybe there is no simple way.
BTW—I'm using AngularJS, if there are any built in methods—though I think this is mostly just a javascript thing.
Thanks a bunch!
It looks like a bad idea, but... well, if it is imperative...
It makes no sense to change a script in a <script> tag - if it is in DOM, it has already executed (and no longer matters). Thus, to change the script before it has a chance to execute, you need to load it using AJAX, change the text, then eval it.
You can easily change the variables. Refer following steps
Include external script just below the script you have written.
Access the variables in the external script as if they are locally declared.
The variables you have created in above script are available in global scope and hence should be accessible from everywhere.
Note: This answer was added before the function clause was added.

How can I get a user control property through the client?

I am creating a few user controls that will inherit from my class, BaseControl, which inherits from UserControl. BaseControl is going to include some "stuff" that I'll need. One of them is a string property called ControlValue. I need a way to access that from JavaScript. I've been reading a bit about RegisterExpandoAttribute(), but I'm not sure how to get it to work or where I should put it as the property can change values at anytime. I would prefer to avoid hidden fields.
Any help would be appreciated.
The best way to do this depends on many things. Like what kind of HTML your custom control is creating.
However, the most general way (the way that will work in all cases) is to register some javascript that sets a global value.
Something like this should work:
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(this.GetType(), "setupglobal",
"<script type=text/javascript>var hiImAGlobal = 'sam'; </script>");
Remember, I'm not saying this is the BEST way, just a way that will work.
Here is the MSDN documentation:
http://msdn.microsoft.com/en-us/library/asz8zsxy

In Yii, pass PHP variables to JavaScript

In my JavaScript (using jQuery) there are a whole set of PHP variables to which I need access. While I've got it working by just producing the JavaScript file as a view, and then using renderPartial() to echo the JavaScript inside the main view.
However, this is obviously not very elegant, so I would like to know the 'Yii' way of doing it. I've been looking at the Assets Manager but that seems to be for static JavaScript files - you can't include PHP in there (unless I'm wrong).
Is there another way of doing it?
You may consider registerScript. In my opinion, it is better since there is a param named $position, which can help you control the process output of render().
There's nothing inherently wrong or inelegant with your approach, and yes assets are static content (JS, CSS, etc) -- unrelated to the issue.
Fundamentally you can only expose the value of a PHP variable in JS by writing it as part of PHP code. If you will only need this value in a limited scope then you could just write it as an inline constant (which is what e.g. some widgets do). If you need it to be available throughout your JS code the only option is to produce JS code like you do now.
It's not strictly necessary to make a new partial view for your PHP-to-JS variables, but it's also not a bad idea. If you are happy with it, by all means use it.
The one of approaches is to set global variable by a small script and redisterScript(), and then use this variable in real js
Setting your variables in a key=>value array and using CJSON::encode works really well. You can access all your variables via the object created by jQuery's parseJSON. For example:
$myVarList = array(
'nameOne'=>$valueFromAnotherVar,
'nameTwo'=>$object->coolValue,
'nameThree'=>$cat->hoursSleptToday()
);
Yii::app()->clientScript->registerScript("myVarList",
'myVarList = jQuery.parseJSON('.CJSON::encode($myVarList).');'
You can then access the values from the global var.
myVarList.nameOne || myVarList.nameTwo || myVarList.nameThree
Refer to Yii2 - Client Scripts Documentation, you can use registerJS function to pass variables to javascipt. For example:
/* #var $this yii\web\View */
$this->registerJs(
"var calenderEvents = ".Json::encode($calenderEvents).";",
yii\web\View::POS_HEAD,
'calender-events-script'
);
Try to do this that way:
$myVarList = array(
'nameOne'=>$valueFromAnotherVar,
'nameTwo'=>$object->coolValue,
'nameThree'=>$cat->hoursSleptToday()
);
$json = addslashes(CJSON::encode($myVarList));
Yii::app()->clientScript->registerScript("myVarList", 'myVarList =
jQuery.parseJSON("' . $json . '");');

What is common AJAX convention for knowing a particular state when a page is loaded?

This has been a question I've had since I started doing serious ajax stuff. Let me just give an example.
Let's say you pull a regular HTML page of a customer from the server. The url can look like this:
/myapp/customer/54
After the page is rendered, you want to provide ajax functionality that acts on this customer. In order to do this, you need to send the id "54" back to the server in each request.
Which is the best/most common way to do this? I find myself putting this in hidden form forms. I find it easy to select, but it also feels a bit fragile. What if the document changes and the script doesn't work? What if that id gets duplicated for css purposes 3 months from now, and thus breaks the page since there are 2 ids with the same name?
I could parse the url to get the value "54". Is that approach better? It would work for simple cases repeatedly. It might not work so well for complex cases where you might want to pass multiple ids, or lists of ids.
I'd just like to know a best practice - something robust that is clean, elegant and is given 2-thumbs up.
I think the best way to do this is to think like you don't have Ajax.
Let's say you have a form which is submitted using Ajax. How do you know what URL to send it to?
The src attribute. Simply have your script send the form itself. All the data is in the form already.
Let's say you have a link which loads some new data. How do you know the URL and parameters?
The href attribute. Simply have the script read the URL.
So basically you would always read the URL/data from the element being acted upon, similar to what the browser does.
Since your server-side code knows the ID's etc. when the page is being loaded, you can easily generate these URLs there. The client-side code will only need to read the attributes.
This approach has more than just one benefit:
It makes it simpler where the URLs and data is stored, because they are put exactly in the attributes that you'd normally find then in HTML.
It makes it easier to make your code work without JavaScript if you want to, because the URLs and all are already in places where the browser can understand them without JS.
If you're doing something more complex than links/forms
In a case where you need to allow more complex interactions, you can store the IDs or other relevant data in attributes. HTML5 provides the data-* attributes for this purpose - I would suggest you use these even if you're not doing HTML5:
<div data-article-id="5">...</div>
If you have a more full-featured application on the page, you could also consider simply storing your ID in JS code. When you generate the markup in the PHP end, simply include a snippet in the markup which assigns the ID to a variable or calls a function or whatever you decide is best.
Ideally your form should work without javascript, so you probably have a hidden form input or something that contains the id value already. If not, you probably should.
It's all "fragile" in the sense that a small change will affect everything, not much you can do about that, but you don't always want to put it in the user's hands by reading the url or query string, which can be easily manipulated by the user. (this is fine for urls of course, but not for everything. Same rules that apply to trusting $_GET and query strings apply here).
Personally, I like to build all AJAX on top of existing, functional code and I've never had a problem "hooking" into what is already there.
Not everything is a form though. For
example, let's say you click a "title"
and it becomes editable. You edit it,
press enter, and then it becomes
uneditable and part of the page again.
You needed to send an ID as part of
this. Also, what about moving things
around and you want those positions
updated? Here's another case where
using the form doesn't work because it
doesn't exist.
All of that is still possible, and not entirely difficult to do without javascript, so a form could work in either case, but I do indeed see what you're saying. In almost every case, there is some sort of unique id, whether it's a database id or file name, that can be used as the "id" attribute of the html that represents it. * Or the data- attribute as Jani Hartikainen has mentioned.
For instance, I have a template system that allows drag/drop of blocks of content. Every block has an id and every area that it can get dropped has one as well. I will use prefixes on the containing div id like "template-area_35" or "content-block_264". In this case, I don't bother to fallback w/o javascript, but it could be done (dropdown-> move this to area for example). In any case, it's a good use of the id attribute.
What if that id gets duplicated for
css purposes 3 months from now, and
thus breaks the page since there are 2
ids with the same name?
If that happens (which it really shouldn't), someone is doing something wrong. It would be their fault if the code failed to work, and they would be responsible. Ids are by definition supposed to be unique.
IMHO putting is at a request parameter (i. e. ?customerId=54) would be good 'cos even if you can't handle AJAX (like in some old mobile browsers, command-line browsers and so) you can still have a reference to the link.
Apparently you have an application that is aware of the entity "Customer", you should reflect this in your Javascript (or PHP, but since you're doing ajax I would put it in Javascript).
Instead of handmaking each ajax call you could wrap it into more domain aware functions:
Old scenario:
var customer_id = fetch_from_url(); // or whatever
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
New scenario:
var create_customer = function (customer_id) {
return {
"dosomething" : function () {
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
},
"dosomethingelse": function () {
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
}
};
}
var customer_id = fetch_from_url(); // or whatever
var customer = create_customer(customer_id);
// now you have a reference to the customer, you are no longer working with ids
// but with actual entities (or classes or objects or whathaveyou)
customer.dosomething();
customer.dosomethingelse();
To round it up. Yes, you need to send the customer id for each request but I would wrap it in Javascript in proper objects.

Categories

Resources