Course Content

Course Content

JavaScript Cookies

JavaScript cookies

Hello guys, welcome to our series on JavaScript. In the last segment, we learned how to validate form and email and finished the module on validation. I hope you have practiced the practicals in the last segment. Now let us move on to cookies in JavaScript and learn how to use them. The next four segments will be about cookies.

What are cookies? Suppose we pass a request on our web browser. For instance, if I search something on my web browser, the results are not directly found on the web browser, they are first sent to the server as requests, And then the server responds to those requests. For example, if I open the Chrome browser to visit the LearnVern site, and go to the HTML course to open a segment, to watch the video, the request is first sent to the server of LearnVern and then as a response, we can view the video. It is not true that all the videos are hosted by the website, the videos are hosted by the server. So, whenever we want to watch a video, a request is generated and sent to the server, and as a response, we get the video from the server. This was an example, from that example, what do we understand? When we search through a web browser or we want to do something else if a server exists related to that, then a request will be generated from our browser and will go to the server and on the server, the code will be executed and on that basis, a response will be generated and that response is again received in the browser and then the output is visible to us to tell you that the tasks performed on a web browser are requests that are sent to the server and the code is executed on the server and a response is generated and then output is visible to us.

For example, if I go to Google, and search LearnVern, as you can see, we have the website on top of the list but when I typed LearnVern a request was sent to the server of Google and as a response, or output we get the website. Along with the website, we get all the other related information about LearnVern like videos, documents, etc. on other websites will also be fetched. That’s why when we searched for LearnVern, we got more than one result. We can also find there are LinkedIn, Facebook, and other social media links. So the response to any request is visible within the browser. Basically, the request is sent to the server and is returned to the browser as a response. But, there is an additional detail to this, sometimes along with the request we also have to send data multiple times.

For example, we create a user and we want all the information related to the user. If we are accessing an application related to banking, there will be more than one facility on the application. We are not provided with the output for all the facilities collectively, instead, we have to check it one by one. So when we keep shifting from one facility to the other it keeps checking the user to provide the information. So the data of the user is not checked one time but is checked multiple times. So if we have to add the user data multiple times, as in every time we run a facility, it becomes hectic for us. It means that the user does not like entering the same information multiple times. In such cases where we require authentication multiple times from the user, but we don’t want to do it time again, we need to store it, we use cookies. Cookies are temporary storage in which we add data to request and we get a response and in case we need that data for authentication again, we don’t ask the user for it again. We use the data stored in the cookies to generate requests and the response is generated. After entering the data once, for all the times we need information, we use the same cookie.

So basically what is written is “an amount of information that persists between a server-side and a client-side as cookies are used in the interaction between server and client. A web browser stores this information at the time of browsing.” When we are browsing, the web browser stores the information at the same time. It means that for instance, if I go to the LearnVern website and log in, once I log in, my data will be stored here, which means I don’t have to log in multiple times and I don’t have to enter my email address and password every time. We log in one time, that’s enough. As long as I keep the tab open I can access the content of LearnVern as many times as I want without logging in again since the data is stored in the cookies. So our website or application will not ask the user for an email address or password time and again, it will store the details in its cookie. Until the time we don’t close the tab, the data will be saved in the cookie. So this was the part where I explained the basic definition of cookies.

In cookies, name-value pairs are created. Name-value pairs means when we want to create cookies we store the data under name-value cookies. Like username = A B C D, password = 1 2 3 4, first name = whatever our first name is. So here our attributes like username, password, first name, etc. are called names, and the value we enter for these names, for example, the company name is my name and the value is LearnVern. So in this way, cookies are stored in name-value pairs.
-8:00

So here let’s look at how cookies work. The flow that I just told you about is mentioned in the slide. “When a user sends a request to the server, meaning when I send a request to the server, then each of those requests is treated as a new request sent by a different user.” This means that the server considers each request is coming from a different user. “To recognize the old user, we need to add a cookie with the response from the server.” Basically, since the server assumes every request is coming from a different user, New user. To avoid this, what does the server do? it shares some data as responses to check that the request we received came from an existing user or new user? Then it stores the data so that it can distinguish between existing and new user. So “now, whenever a user sends a request to the server, the cookie is added with that request automatically.” This means we add the cookie to the client request so that the server does not have to check the information. With the help of a cookie, while the request goes to the server, it will be easy for the server to identify that the request is sent from an old user and thus provides the data related to the existing user as a response. “Due to the cookie, the server recognizes the users.” The server identifies the user easily. Here, how to create a cookie? Here in JavaScript, so what I just mentioned is the name and LearnVern is the value. So document dot cookie is a way to define a cookie in JavaScript. We will perform this practically. Here, we will look at an example in the normal flow, so after we look at the example we will see if the program runs or not.

So first of all, I will open sublime text, what we will be doing in the program is, as we are going to write a program for cookies we will take two buttons, with one button we will store cookies in our system and retrieve the cookie stored with the second button. So we are going to execute the “get cookie” and “set cookie” method. First of all, we will type HTML…and start the program. HTML (typing pause 4 seconds) example, Cookie, this script, and then we will save the program.

Okay, so our program is saved. Now we need two buttons in the body. Input type equal to button.. value equal to Set cookie is the name of the button. And when we click on it..the set cookie method will also be executed. Save. After the cookie is set we will get it. Once we perform get cookie we will get an output of the cookie that is stored. So if we have created two functions we also have to write its code.. Our first code will be a function for the set cookie. So it is simple, similar to what we learned in the slide we will be setting cookies. Now we will store a static cookie, so document dot cookie, equal to let’s type the company name…equal to LearnVern. So whenever we press the button named set cookie the value of the company name will be set as LearnVern. Similarly, we have a function called get cookie which we have to create. So function get cookie. Since we have to get the cookie we will strike the document dot cookie and check it because once the cookie is set we will get an output. If document dot cookie dot length is not equal to zero.

This is an array. This means if we store more than one cookie, the cookie is stored in the form of an array. We are only storing one cookie value here, but if we were to store more than one value of cookie then it is stored in the array of cookies. This is why we are checking the document dot cookie dot length properly and the length means that if the array has one or more than one cookie, then we will get a return. Alert dot document dot cookie. So the cookie stored inside will be shown.

Else if it is not true then (4 seconds pause) Else, Alert the cookie is not set. This is done. We will now run the program. (6 seconds pause) So here is our program. In this program, we know that when we click the get cookie button we get the cookie that is set. So let’s say I click the get cookie, since we have not set a cookie we are getting an output that says that cookie is not set. Let’s click set cookie which means the cookie is set. Now I will click get the cookie and again I get an alert saying the cookie is not set. When we click on the set cookie button this line in the program gets executed. So although we are clicking set, it has not been set. There is a reason for this, why is this? When I was explaining cookies to you, you must have noticed that the client and the server are in the picture which means when the request is sent from the client to the server we get a response from the server. So when it comes to cookies, the domain is very important. This means that when I am executing the program you can see in the url that this is my local address. It implies that the program stored in this location is run in the browser. Cookies don’t run when we use programs in local storage. To run a cookie, we need a server.

So if I am working locally how can I generate a server? We download XAMPP for this purpose, there are other servers available for this but we will be using XAMPP. So the reason why the cookie is not being set is that the program is in local storage and we have to host it to the server. So how to make a server in the local program is by downloading XAMPP. This is the website of XAMPP and you can download whichever suits you the best. My system is Windows, if your system is Linux-based then you can download the Linux version. You can download the appropriate software for your operating system. So currently I will download it and there are other versions of this you can download any of them. It is not compulsory to go with the latest one. You can download any one version. Currently, I will download this version, it is being downloaded. It has been downloaded. This is an installer file. I will run the file. While installing, click next a few times, and this is the folder where it will be saved, in the C drive XAMPP folder. Let’s leave it in C. Next, language. The installation is being started. (pause 4 sec) We have to wait until all the files are installed for a successful installation of XAMPP. So now the installation is complete and you have to click on finish. When you install the XAMPP for the first time, this window will automatically open. If this does not happen and if you have to open XAMPP every time you run a program, then to change this you can go to start and open XAMPP. This is XAMPP. Initially, when we want to run a program through XAMPP, we have to first close our cookie program from this panel. We have to close our program. To do this, we need a server, as you can see Apache is a server and you can start this server. When you click the start the button will change to stop. This is in the running mode which means my server is running.

Now how do we run our program with a cookie? First of all, we will go to the C drive and then to the XAMPP folder, and in it, there is a folder called HTdocs. We enter it and save all the cookie-related documents in this folder. Normally all the programs that we want to run on the server should be saved in the HTdocs folder. I’ll rename it (pause 4 sec) JavaScript. I will place my file inside this folder. But if you remember this file is saved in HTML format. We cannot save it in this folder in HTML format. Servers are mostly used to run PHP files. So we have to save the same file with a dot PHP extension. So I will copy this and paste it here. I have selected PHP here. It is not compulsory; you can also edit it as cookie dot PHP while you are saving the program. Now I have to save this program in JavaScript. So first I will change C, XAMPP, HTdocs, JavaScript, and here I will save the program called a cookie. My program has been saved. Because our XAMPP is started, we write localhost, we don’t need this line. We get 8000. Why 8000? Because I have set my configuration file’s port number 8000. The local host will run on the port number. When I type localhost and 8000, it automatically adds a dashboard to it and I can see the XAMPP related page. But in my HTdocs there is a Javascript folder that consists of programs. So (typing pause 4 sec) I open JavaScript. So as you can see, when I added JavaScript I can see the program cookie dot PHP. When I click on it, the program runs, as you can see. So now we have a server and I have run a program through a server.

When I click get cookie, I receive cookie is not set. Let’s say if I click on the set cookie button, and then press get cookie I receive the company name equal to LearnVern. So the cookie is set. Did you understand? So to set the cookie we had to install XAMPP server. It is not a rule to install XAMPP, you can download any software that is relevant to you. This was the normal way to do it. We also learned how to install XAMPP.

So not only in JavaScript but also in PHP when you require a server to access a program, you can use XAMPP and use our segment as a reference to installing it. So please note that when we run a cookie program we require a server and without a server, we cannot run it. It is necessary to have a server like XAMPP or WAMP. Here we have set the cookie company name equal to LearnVern.

If you have any queries or comments, click the discussion button below the video and post there. This way, you will be able to connect to fellow learners and discuss the course. Also, Our Team will try to solve your query.

Guys, we will conclude this segment here, and we will continue the same topic in the next segment. Till then keep practicing, goodbye.

Share With Friend

Have a friend to whom you would want to share this course?

Download LearnVern App

App Preview Image
App QR Code Image
Code Scan or Download the app
Google Play Store
Apple App Store
598K+ Downloads
App Download Section Circle 1
4.57 Avg. Ratings
App Download Section Circle 2
15K+ Reviews
App Download Section Circle 3
  • Learn anywhere on the go
  • Get regular updates about your enrolled or new courses
  • Share content with your friends
  • Evaluate your progress through practice tests
  • No internet connection needed
  • Enroll for the webinar and join at the time of the webinar from anywhere