How to get the values of session using js - javascript

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

Related

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,

Passing data from one page to another

Pls can anybody give me the clue of how to pass data from one page(test1.html) to another page(test2.html) and then later pass the previous 2 pages(test1 and test2.html) to a new page called last.html using javascript not php cos it is a local app. tanx
There are several ways to do it, you could pass a query string from page to page (prob a bad idea unless we are talking small bits of data you dont mind people seeing)
You could use local/session storage depending on the browsers you are looking to support.
You could also use a database and have a ajax post/get from page to page (not a great idea)
If you have something like php in the back end you could use a php session.
You could also use a cookie (again not the best idea but a good fallback for local/session storage)
Or you could have a single page app and use something like angular to show/change your page(s)

How do I populate form fields on a page from a database based on the page url?

Hello first I’d like to say, please excuse my ignorance to this all, as I’m very new to this all. I just started and still trying to understand this.
So far I have a database set up and I’m trying to retrieve values from a database to fill in a form on a page when it loads. The record or row/values that need to be retrieved from a database depend on the page’s URL.
I’m ok with html and css but still trying to learn more about jquery, JavaScript, sql, php and so on and so forth. I realize I have a ways to go and honestly some of the guides and tutorials online are kind of confusing because everyone has a different way of coding. So I’m a bit confused.
I’ve included a simple chart to breakdown what I’m trying to do.
If someone could point me in the right direction I’d be really grateful! Thanks.
If I understand you well, you want to setup a form and populate some fields of this form with a query forms a database, the primary key of the record being relative to the url.
The first step is to build the url, you can pass some parameters to an url by adding a ? at the end of the url followed by the parameter name, the = sign and the parameter value. If you have more than one parameter, you should separate each parameter with the sign &.
So your url could be something like this :
www.examplesite.com/page&.html?key=key_A1
Then, you'll have to choose if you want to build the page on the server side with a language like php, in which case you retrieve the parameter, query the database, build the html form and send it to the client.
You can also go client side with plain javascript or jquery, in which case you will still have to do some server side programming to query the database but will use an ajax call to get the data and will populate the fields in Javascript or JQuery.
You can do this using Javscript(using Ajax)
U need the key to search for get the results from database
Using ajax call get the data, You might have to write code to get the details from database using any server side prog language
Using javascript to fill the form input with the received data.
Google for jquery ajax examples, and how to populate input using javascript.
There are many frameworks out there that have DataBinding built-in that do the same job a lot easier. My favourite would be Angular Js, you can try Ember and lot more out there, choose the one you feel comfortable with.

Special URL for language selection?

Just a simple question, I was wondering why some websites have something like "?lang=EN" in their URL after selecting a language? Is it because their html file or folder containing it is named "?lang=EN", or some other code that does this? I'd like to set the URL like that for my website (has 2 languages). Currently I have folder structure like this:
Language selection: D:/media/index.html
EN site: D:/media/en/index.html
CN site: D:/media/cn/index.html
Files for the website: D:/media/site
Thanks.
First of all, anything after the file extension ( .html ) is a server side function.
The ? is a function for PHP and adds variables to the super global GET array ( in the form: ?variable=value&variable2=value2 ) that is directed to from another page and from that point many things can be done with the data.
Sites that use the ?lang=EN are probably programmed to print out the chunks of text needed on the single page in the places and languages required. Though it is possible using this method to redirect to a language specific directory.
Hope this helps :)
That's because they often have a content management system where the content isn't stored in files necessarily, but in a database. The lang=en is a GET variable from the URL that they retrieve in, for example, PHP, to display the correct content. In your case, however, you can just redirect the user if they click EN or CN to the appropriate locations, in your case, /en/index.html and /cn/index.html.
The url you see at the address bar, whatever comes after "?" is called "QueryString" and with libraries on the server side (based on the developing platform that website is made on) you can access the values. For instance the value of "lang" can be equal to "EN" or "CN" etc.
By the way you can have some http handlers to rewrite the requested url and get your parameters through the url that physically doesn't exists. Like the one you mentioned, "http://yoursite.com/en/default.whatever". I myself prefer this way but as you requested you should use some server side libraries to access the query string values and choose the language of the content you wanna send to client.
Also as one solution that once I used, you can also use some translation service (like translate.google.com) client libraries and call it at client side with jquery or even javascript and translate all the texts on page load. Although it's damn fast in action, it has some issues you will see.
Hope it helps.
PHP uses $_GET to get value from variables from the URL.It gets the value from that LANG variable and then it selects all from a file where are stored all the words in different languages or from the database
You don't need to copy every file and then translate it.
Search for php dynamic pages tutorial in your case. I found THIS.
P.S. PHP is one from many ways to do this.

Obtaining value obtained by javascript using PHP

I was able to extract user information from the social Graph API and display it on my site within tags . How do I now get this information, and use it in a PHP script? In other words, say I want to use PHP to calculate the weather, but only based on the preferred weather on a users facebook profile(hypothetical situation). Now, assuming I have obtained the users preferred weather using javascript, how do I use PHP to get that information in order to perform my calculations? I guess one way would be to use regular expressions to match the values on the same page, but that seems tedious. Any help/direction is appreciated.
Are you using php to access the Facebook API or the pre built HTML they provide? You should use php to retrieve the data, do what you need to do with the data, and then display it on a webpage, rather than the other way around.
You can use javascript to get the data, then send it to your php script using AJAX, but this is a round-about way of doing it.
You can make the call the to the Graph API directly from your PHP script. Something like this:
$r = new HttpRequest('https://socialgraph.googleapis.com/<method_name>', HttpRequest::METH_GET);
You will need to parse the data when you get the response -- json_decode() should do the trick.

Categories

Resources