<script type="text/javascript">
var a = "{{Django_Variable}}"
</script>
I get this idea.
But what if these Django Template variables contain sensitive information? I have written a Javascript application that needs to receive data from Django, but my current implementation shamelessly displays all the details in developer mode.
<script>
$(function() {
MyApp.init(
userid: 46,
hasPermission: False,
secretData: "Not anymore",
...
);
});
</script>
The data I'm trying to pass in are not as sensitive as credit card or password information, but sensitive enough that I need to hide it. I have considered firing AJAX GET after the page loads, but that just adds extra overhead.
How do I pass in Django Template variables to my Javascript without showing it in HTML?
Thank you.
There are no real differences when it comes to this whether it be django or any other framework . The problem inherently has to do with the fact that javascript is client side technology.
However yes ajax request is one possible . Others can be minifying/encrypting etc ... Anything that you would use for any other framework. I would say you should read these answers to get a better picture:
Secure data in JavaScript
Related
I want to know if the user has logged in or not and then display different elements of the navigation based on the username (login by email and password Not username). However, I have no idea how to deal with session. If php and html is separated in two documents, how can I store the required values using session in php document and then get them using javascript in html document? Or should I use cookies instead?
There are a several approaches to do this.
1) You can make a PHP file which will format your $_SESSION data, and all the other data you want as a JSON string (json_encode function in PHP lang). Then use echo to return it. Then use an AJAX request to get this file from javascript or JQuery, and you will receive the data you want. That's a bad approach for this purpose, from my point of view, because after loading the page you send another request to receive a static data, which will not change on the page like email or username.
2) Better approach: PHP is preprocessor hypertext. You can make an php file and write html tags in it, with php output(example: <div><?=$_SESSION['email']?></div>). Search for more info in google ("php inside html").
3) Much better. In modern web programming world its a mistake to use php inside html because you should think not only about how to make something work, you should think how you will maintain it after 3, 6, 12 months later, too. If you use just php inside html in a big project, then, with time, you realize that your code is hard to read and looks ugly. There are plugins that can make your view more readable and maintainable (Twig, Blade, Volt and others). I recommend you use one of them.
The session is a server side thing, you cannot access it using javascript. You can write an Http handler (that will share the sessionid if any) and return the value from there using AJAX
I have a fairly large Application and I'm currently trying to find a way around having to pass Data from PHP (User Tokens for 3rd Party API's and such) through the DOM. Currently I use data-* attributes on a single element and parse the Data from that, but it's pretty messy.
I've considered just making the contents of the element encoded JSON with all the config in, which would greatly improve the structure and effectiveness, but at the same time storing sensitive information in the DOM isn't ideal or secure whatsoever.
Getting the data via AJAX is also not so feasible, as the Application requires this information all the time, on any page - so running an AJAX request on every page load before allowing user input or control will be a pain for users and add load to my server.
Something I've considered is having an initial request for information, storing it in the Cache/localStorage along with a checksum of the data, and include the checksum for the up-to-date data in the DOM. So on every page load it'll compare the checksums and if they are different (JavaScript has out-of-date data stored in Cache/localStorage), it'll send another request.
I'd rather not have to go down this route, and I'd like to know if there are any better methods that you can think of. I can't find any alternative methods in other questions/Google, so any help is appreciated.
You could also create a php file and put the header as type javascript. Request this file as a normal javascript file. <script src="config.js.php"></script> (considering the filename is config.js.php) You can structure your javascript code and simply assign values dynamically.
For security, especially if login is required, this file can only be returned once the user is logged in or something. Otherwise you simply return a blank file.
You could also just emit the json you need in your template and assign it to a javascript global.
This would be especially easy if you were using a templating system that supports inheritance like twig. You could then do something like this in the base template for your application:
<script>
MyApp = {};
MyApp.cfg = {{cfg | tojson | safe}};
</script>
where cfg is a php dictionary in the templating context. Those filters aren't twig specific, but there to give you an idea.
It wouldn't be safe if you were storing sensitive information, but it would be easier than storing the info in local storage,
I am getting records from database in my HTML
<g:each in="${index}">
${""+it.indexDate+""+it.value }
</g:each>
It's working fine, but I want to use this record below in my javascript:
I want to do some thing like this
<SCRIPT LANGUAGE="JavaScript">
if(it.value>10){
alert("yes")
}
Is there a way I can do that?
Apparently you want to do exactly the same as what is described in this question.
Trying to access your database directly Javascript might be feasible but it is never a good idea.
In fact, the Javascript runs on the client side, and you don't want your clients to be able to mess up with your data. I would highly recommend using Ajax. That is to say, be able to asynchronously call the server side (PHP or any other server-side language you use) from the client side to request what you need from the database.
Maybe you can help me understand some pretty basic stuff here. I am new to jQuery and web in general (though I have a lot of winforms / win32 experience). I have a website that runs on Google App Engine and uses Django and jQuery. The website is used to order a service. It has three forms:
A form in which you describe yourself (e.g you input name, address and so forth) you click next and then the following form appears:
A form in which you input the info of the service you want, such as service name and date. this form needs to display the data you entered in the previous form (form 1) in case you forgot something. you click next, and then the system needs to save all the data you wrote so far, and process your request for a service (this is done at the server side). this form is now displayed:
A form which shows a summary of your service request (and allows you to do other things such as sending the info to other people and so forth).
How would you transfer the data from form 1 to form 2 and then to the server? POST? is this safe? how will you do this in code? is there a way to transfer JS objects?
Make one form in one page and using JavaScript display sections of the form as needed. As far as submitting form values is concerned, you can either submit directly to script via form attribute action="...script url..." , or if you choose to employ AJAX you can use JavaScript or use jQuery's $.post().
This is a pretty open ended question.
So I'll start with one of the unnumbered questions first: "Is this safe".
The quick answer is probably no.
Here's some examples of how to answer that question:
Example:
I want to make a javascript app that
can collect data. I will hold all
data in this javascript object.
1: Is this safe. 2: No it's not, it
can be manipulated by anyone with a
browser.
Example 2:
I will just transmit that stuff via GET or POST to my
server and then mess with it there.
1: Is this safe. 2: No it's not, I
don't really get how stuff is stored
and my ignorance will cause my data to
get stolen.
Example 3:
I totally understand my server and my
initial page.
1: Is this safe. 2: No it's not,
unless all of my data is transmitted
over SSL/TSL it is widely available to
nefarious uses.
Example 4:
I have an SSL service and I understand
everything about my data transmission. I need to
store my information to retrieve it later.
1: Is this safe. 2: No it's not. I am using Google App engine so I'm just a trusting individual OR I'm using S3 and I trust them. or I'm using a sql server with whatever os and I trust those vendors, etc.
Example 5:
I feel ignorant that I just blindly
trust my vendor.
1: Is this safe? 2: No it's not.
(Obviously)
All that said you're using a Google App Engine backend so there's a ton of help on this.
Sorry it's my birthday and your question caused me to wax philosophically while I waste the day at work.
But remember, the prudent answer to "Is it safe" is always "No"
Can we do client side validation using AJAX in struts 2 application ?
If yes, then please let me know the procedure.
Answer is right here.
http://struts.apache.org/2.x/docs/ajax-validation.html
even provides prototype example instead of dojo
As Sergio said, you could use this, for example, in a registration form where you have fields like:
Username
E-mail
Password
Repeat Password
You can set up some javascript to validate the form before the user submits it, or better yet, don't enable the submit form until all required fields are complete, avoiding user frustration (you tell him specifically where the error is and how to correct it) and adding another layer of validation to it.
In this case you can pre-validate Username and E-mail against the server to see they are not taken yet. You can do something like this (in jQuery, from memory):
$("#email").change(function(e) {
var $elem = $(this);
var val = $elem.val();
if (!val) {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
} else if (!/^[a-z0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i.test(val)) {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
} else {
$.getJSON("isEmailAvailable.php", {email:val}, function(result){
if (result.available) {
myMarkField($elem, "valid");
myValidateForm("myForm");
} else {
myMarkField($elem, "not-valid");
myValidateForm("myForm");
}
});
}
});
Where isEmailAvailable.php should return something like { available: true }
AJAX is the mechanism by which you could invoke the server-side validation. The "J" in AJAX stands for Javascript.
You would typically make use of AJAX (and hence Javascript) to invoke some sort server-side validation that would be inappropriate for client-side validation. For example, the validation of a zip code against a table of acceptable values.
How would you do this? You use JS for client-side programming (including validation), it has nothing to do with the server side.
Additionally: server-side-validation via the client-side JS would be a bad idea, as all your validation code would be exposed to the user.
If your going to do server-side input validation then what do you need to use JavaScript for?
I'll make the assumption that you are using PHP on the server-side in which case you'll want to validate it there instead of making another unnesicary request.
If you want to use AJAX to do some server-side validation (and you'r using JQuery) this should at least get you started:
function validate(fieldName)
{
$.get('/validation.php',
{'value' : fieldName.value, 'name' : fieldName.name},
function(data, textStatus)
{
if(data)
{
fieldName.style.class = 'validFormInput';
}
else
{
fieldName.style.class = 'invalidFormInput';
}
})
}
I'm no JS/JQuery expert and I didn't test this so it's just to get you started.
I think you need to read a bit about AJAX.
I recommend this link: http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html
I think it's simple and easy to understand.
Basically you have server and client side code. JavaScript (client side) can invoke a URL using Ajax(Asynchronous JavaScript And XML) witch is very similar to invoke any other URL using a browser. The main difference is that there is no page reload.
Your JavaScript will need to be waiting for the reply in order to handle it (in your example show or hide an error message).
Basically it allows you to execute some code at the server an update your page without a page refresh.
In short, the AJAX application architecture enables the client (i.e. a piece of JavaScript running in a web browser) to actively ask for information from a server. Most often, the JavaScript client will use the received information to update small portions of the browser's document using the DOM.
Also, the JavaScript client code can do some obvious validation of e.g. a form to be sent to a server (as shown so nicely by Danita's answer).
The server can be anything. It may just return a plain xhtml file, or may respond to the request by calling a complex PHP script that generates a response. Heck, it may even be a dedicated mobile device entirely implemented in bare C. As long as it implements the http protocol the client's request was transmitted in. This might be JavaScript. Improbable but true.
So Yes: it can be done using 'server-side' JavaScript, if you have a server running JavaScript. But No: that's not probable.
And Yes: you apparently need to read upon AJAX. (I'm not a webdesigner, and even I seem to know more than you ;) Don't leave it that way!)