Send values from django server to client? - javascript

I would like to give some values to my client (to use them in javascript) from my django server.
I know that I can use cookies, but the problem is that they are kept for all request whereas I need them only once when the client loads for the first time (it is not really a problem).
I could also pass those values to the template to render some html tags with the "data-value-name" properties set the the values (for example <body data-name="joe" data-id="123456">)
Both solutions work fine, but is there a better method?

What I usually do is to create a <script> element where I render the values directly to JavaScript objects stored in local or global variables.
If you have a lot of values you can also consider implementing a view that returns JSON which is requested via ajax from the client.

Related

Keeping a global value in the next page [duplicate]

I want to send some data from one HTML page to another. I am sending the data through the query parameters like http://localhost/project/index.html?status=exist. The problem with this method is that data remains in the URL. Is there any other method to send the data across HTML pages using JavaScript or jquery.
why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')
or more permanently:
localStorage.setItem('label', 'value')
localStorage.getItem('label')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I know this is an old post, but figured I'd share my two cents. #Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem and
sessionStorage.myValue = 'value'
in place of setItem.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
Link 1
And, of course, the CORS spec:
Link 2
~Cheers

Alternative to passing Data to JavaScript from PHP?

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,

Live updating from JSON

I have a JSON file which is dynamically and contain match info including an unique id. The JSON is divided into 3 arrays live, upcoming and recent. Since i'm quite new to Javascript i'm wondering what would be the best way to go in order to make this livescore script. I need it to be updating without refreshing browser? What is my options? Maybe someone has a snippet?
The JSON is automatically updates through another script which is connected to a cron job, so the script does not need to do anything regarding the JSON. Only retrieve and show the data.
I'm using dreamhost, which gives me access to shell, so websockets and so on is an option.
You'll need a jquery user to give you a snippit for this one, but in vanilla ecmascript 6, you use an XMLHttpRequest object to get the JSON from your server. This object can request data from the server asynchronously and is triggered by the client/browser so you can update the live match info when and as often as you like. You would just have to write a function to replace the data on the webpage with the new info when it is updated.

Pass PHP class instance through AJAX?

I recently wrote a PHP wrapper class for a new API we are using and have been asked to setup a demo which makes use of it. Certain features can be called directly from PHP, however things such as performing actions on button clicks requires I make use of JS/AJAX.
As I already have an instance of the object in my main PHP file, can I pass this as a parameter to JS and then pass it through Ajax to my handler or is it necessary to establish two separate instances?
The closest thing to doing what you want that I can think of would be copying the PHP object to a JavaScript variable via json_encode and then passing that variable back to your PHP code during the AJAX event via the data parameter. PHP code doesn't persist in the way that you seem to be describing - once a page has been requested by a browser, your PHP code for that page is done, there are no variables persisted by the server after that point.

i18n in javascript using .properties file

I'm developing a web application with JSF, so I use a Java Properties File (i.e. resources_es_CO.properties) to localize strings for the application and this is working OK.
Mi question is: how can I call localized strings in this kind of files from my javascript validations so alerts show those localized strings to user?
Thanks in advance.
What I do is to send the messages out as part of the page, dropped into hidden <span> tags with "id" values made from the property names.
Alternatively, you could write an Ajax-called action and fetch the properties dynamically.
To do an ajax callback, you'd have to implement a server-side action that would understand something like the property key. The server would just apply the localization (ie look up the property in the locale associated with the session) and then return the string. Alternatively, you could implement a service that'd return a whole set of properties, maybe on a per-form basis, or grouped according to some convention of property names (like, "return all properties that start with 'validation.addressForm'")
The simplest case would look something like this with jQuery:
$.get('/fetchProperty', { property: 'firstNameMissing' }, function(propValue) {
$('#errMsg').text(propValue);
}, "text/plain");
Other frameworks provide similar ajax tools, or you could do the XMLHttpRequest yourself.
you could go to server with an ajax call and send alert texts from server to client and show it. or you could put messages to your page when your jsp's being rendered. both is ok. if you can change language without refreshing the page you probably want to make ajax call. if you can not , putting messages in javascript variables will be easier

Categories

Resources