Tutoriale de programare web

  • Generate Random Numbers and Strings in JavaScript
    by Monty Shokeen on 1 februarie 2023 at 3:43

    The ability to generate random numbers or alphanumeric strings can come in handy in many situations. You could use it to spawn enemies or food at different locations in a game. You could also use it to suggest random passwords to users or create filenames to save files. I wrote a tutorial on how to generate random alphanumeric strings in PHP. I began that post by saying that almost no event is truly random, and the same thing applies to random number or string generation. In this tutorial, I will show you how to generate pseudo-random alphanumeric strings in JavaScript. Generating Random Numbers in JavaScript Let’s begin by generating random numbers. The first method that comes to mind is Math.random(), which gives back a floating-point pseudo-random number. The random number will always be greater than or equal to 0 and less than 1. The distribution of the numbers returned in that range is almost uniform, so the method can work well for generating random numbers without noticeable bias in everyday usage. Here is the output of ten calls to the Math.random() method: 1 for(let i = 0; i < 10; i++) { 2 console.log(Math.random()); 3 } 4 5 /* Outputs: 6 0.9981169188071801 7 0.7073616929117277 8 0.05826679080842556 9 0.30779242012809105 10 0.37282814053539926 11 0.8991639574910759 12 0.5851162879630685 13 0.40572834956467063 14 0.5286480734412005 15 0.07898699710613699 16 */ Generating Random Integers Within a Range As you saw in the previous section, Math.random() will give us random numbers in the range 0 (inclusive) to 1 (exclusive). Let’s say we want random integers in the range 0 (inclusive) to 100 (exclusive). All we need to do here is multiply the original range by 100. Taking the first output value from the above code snippet as an example, 0.9981169188071801 will become 99.81169188071801 when multiplied by 100. Now, we can use the Math.floor() method, which will round down and return the largest integer less than or equal to 99.81169188071801. In other words, it will give us 99. The following code snippet will iterate through a loop 10 times to show all these steps applied to different numbers. 1 const max_limit = 100; 2 3 for(let i = 0; i < 10; i++) { 4 let random_float = Math.random(); 5 let scaled_float = random_float * max_limit; 6 let random_integer = Math.floor(scaled_float); 7 8 let rf_str = random_float.toString().padEnd(20, ‘ ‘); 9 let sf_str = scaled_float.toString().padEnd(20, ‘ ‘); 10 let ri_str = random_integer.toString().padStart(2, ‘ ‘); 11 12 console.log(`Random Float: ${rf_str} Scaled Float: ${sf_str} Random Integer: ${ri_str}`); 13 } 14 15 /* Outputs: 16 Random Float: 0.7976037763162469 Scaled Float: 79.76037763162469 Random Integer: 79 17 Random Float: 0.3794078358214559 Scaled Float: 37.94078358214558 Random Integer: 37 18 Random Float: 0.5749118617425708 Scaled Float: 57.49118617425708 Random Integer: 57 19 Random Float: 0.7110572178100005 Scaled Float: 71.10572178100006 Random Integer: 71 20 Random Float: 0.9157559644743132 Scaled Float: 91.57559644743132 Random Integer: 91 21 Random Float: 0.8773095295734263 Scaled Float: 87.73095295734264 Random Integer: 87 22 Random Float: 0.7714603913623834 Scaled Float: 77.14603913623834 Random Integer: 77 23 Random Float: 0.6431998616346499 Scaled Float: 64.31998616346499 Random Integer: 64 24 Random Float: 0.7909155691442253 Scaled Float: 79.09155691442254 Random Integer: 79 25 Random Float: 0.1219575935563590 Scaled Float: 12.19575935563590 Random Integer: 12 26 */ Now that you understand the logic behind the multiplication and flooring, we can write a function that generates a random integer within the maximum limit. 1 function max_random_number(max) { 2 return Math.floor(Math.random() * max); 3 } 4 5 for(let i = 0; i < 10; i++) { 6 console.log(max_random_number(100)); 7 } 8 9 /* Outputs: 10 35 11 23 12 92 13 94 14 42 15 9 16 12 17 56 18 40 19 21 20 */ What if you want to generate random numbers that are above a specified minimum value but below the maximum value? In this case, you can add the minimum value beforehand to make sure that the generated number is at least equal to the minimum value. After that, you can simply generate a random number and then scale it by max – min before adding it to the minimum possible value. 1 function min_max_random_number(min, max) { 2 return min + Math.floor(Math.random() * (max – min)); 3 } 4 5 for(let i = 0; i < 10; i++) { 6 console.log(min_max_random_number(50, 100)); 7 } 8 9 /* Outputs: 10 96 11 81 12 95 13 56 14 73 15 72 16 71 17 90 18 51 19 53 20 */ Generate Cryptographically Secure Random Numbers The Math.random() method is not suitable for generating cryptographically secure random numbers, but the Crypto.getRandomValues() method can help us here. This method fills the passed array with cryptographically secure pseudo-random numbers. Keep in mind that the algorithm used to generate these random numbers may vary across user agents. As I mentioned earlier, you need to pass an integer-based TypedArray to the method for it to fill it with random values. The original contents of the array will be replaced. The following code will fill our ten-element array with random integers. 1 let random_values = new Uint8Array(10); 2 console.log(random_values); 3 // Outputs: Uint8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] 4 5 crypto.getRandomValues(random_values); 6 console.log(random_values); 7 // Outputs: Uint8Array(10) [ 207, 209, 1, 145, 70, 111, 21, 141, 54, 200 ] The Unit8Array() constructor gave us an array of ten 8-bit unsigned integers. The array values are all initialized to zero. Once we pass this array to our getRandomValues() method, the value of random numbers will stay between 0 and 255. You can use other typed arrays to generate random numbers in different ranges. For example, using an Int8Array() constructor will give us an array with integer values between -128 and 127. Similarly, using a Uint16Array() will give us an array with integer values up to 65,535. 1 let random_values = new Int8Array(10); 2 console.log(random_values); 3 // Outputs: Int8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] 4 5 crypto.getRandomValues(random_values); 6 console.log(random_values); 7 // Outputs: Int8Array(10) [ -82, -106, 87, 64, 42, -36, -53, 27, -38, 4 ] 8 9 10 let random_values = new Uint16Array(10); 11 console.log(random_values); 12 // Outputs: Uint16Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] 13 14 crypto.getRandomValues(random_values); 15 console.log(random_values); 16 // Outputs: Uint16Array(10) [ 47615, 60195, 53177, 15169, 215, 4928, 12200, 6307, 30320, 20271 ] Generate a Random Alphanumeric String in JavaScript We will now use the knowledge gained in the previous section to generate random alphanumeric strings in JavaScript. The concept is pretty simple. We will begin with a string that contains all our desired characters. In this case, the string will consist of lowercase letters, uppercase letters, and numbers from 0 to 9. You probably already know that we can access the character at a particular position in a string by passing it an index value. All we need to do to generate random alphanumeric strings is generate random numbers and then access the character at that random index to append it to our random string. The following code snippet wraps it all up in a nice little function: 1 const char_set = ‘abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’; 2 3 function max_random_number(max) { 4 return Math.floor(Math.random() * max); 5 } 6 7 function get_random_string(length) { 8 let random_string = ”; 9 10 for(let i = 0; i < length; i++) { 11 random_string += char_set[max_random_number(char_set.length – 1)]; 12 } 13 14 return random_string; 15 } 16 17 console.log(get_random_string(20)); 18 // Outputs: lgtuRJZolu7AXj4HMoiM 19 20 console.log(get_random_string(40)); 21 // outputs: scOoal3VXgeAjaHIieolhi2TyWFpAn5bBPPiX6UG Using toString() to Generate Random Alphanumeric Strings Another approach that we can take to generate random alphanumeric strings is to use the toString() method on our randomly generated numbers. The toString() method returns a string that represents our specified numerical value. This method accepts an optional radix parameter that specifies the base in which you want to represent the number. A value of 2 will return a binary string, and a value of 16 will return a hexadecimal string. The default value of this parameter is 10. The maximum value can be 36 as it covers all 26 letters and 10 digits. Here is the output of a few calls to this method for different radix values: 1 let number = 3498650143868; 2 3 console.log(number.toString(2)); 4 // Outputs: 110010111010010111110011001000110001111100 5 6 console.log(number.toString(10)); 7 // Outputs: 3498650143868 8 9 console.log(number.toString(16)); 10 // Outputs: 32e97cc8c7c 11 12 console.log(number.toString(36)); 13 // Outputs: 18n99yoak You might have noticed that the length of the output string keeps decreasing as we increase the radix. In the following code snippet, we will use our max_random_number() function from the previous section to get a random number. We will then convert this random number to an alphanumeric string by using the toString() method. 1 function max_random_number(max) { 2 return Math.floor(Math.random() * max); 3 } 4 5 for(let i = 0; i < 10; i++) { 6 console.log(max_random_number(Number.MAX_SAFE_INTEGER).toString(36)); 7 } 8 /* Outputs: 9 1tr84s6c2sl 10 1yj4varyoj7 11 1zdg9nn0z6r 12 lubrjj1zih 13 13tt2n5vw9t 14 1mv6sctjgf 15 yx3fhnznhf 16 1wj4mdcrqb9 17 26sir75af2r 18 qdv9xv800t 19 */ What if you want even larger alphanumeric strings and want them to have a fixed length like 40 characters or 100 characters? In that case, we can create a loop that keeps appending our generated strings until we reach the desired length. 1 function max_random_number(max) { 2 return Math.floor(Math.random() * max); 3 } 4 5 function get_random_string(length) { 6 let random_string = ”; 7 while(random_string.length < length) { 8 random_string += max_random_number(Number.MAX_SAFE_INTEGER).toString(36); 9 } 10 return random_string.substring(0, length); 11 } 12 13 console.log(get_random_string(40)); 14 // Outputs: bn0nfhcsjm18ylzqrm6bo1iktka2aq7qbbl5ybki 15 16 console.log(get_random_string(100)); 17 // Outputs: rdosjhthsevmk91mj9zvqexz2z0v3pe2beasbzoworanzjg3bfpf975rzfy2fmo6pmj4p69u0x80ce92jh2vljx90g6r0lzd8vb0 Final Thoughts In this tutorial, we learned how to generate random numbers and alphanumeric strings in JavaScript. Generating random integers is easy in JavaScript with the help of the Math.random() method. All we had to do was scale the output so that it matched our desired range. You can also consider using the getRandomValues() method if you want your random numbers to be cryptographically secure. Once we know how to generate random numbers, creating random alphanumeric strings is easy. All we need to do is figure out how to convert our numbers to characters. We used two approaches here. The first one involved accessing the characters at a random numerical index in a predefined string. This technique is useful if you want to be specific about the characters that should be included in the random alphanumeric strings. The other approach involved using the toString() method to convert our decimal numbers to a different base. This involves fewer calls to our max_random_number() function. There are certainly many more techniques that you can use to generate random alphanumeric strings. It all depends on your needs and how creative you want to be with your approach.

  • Vue.js Tutorial: Beginner to Front-End Developer
    by Franc Lucas on 31 ianuarie 2023 at 4:57

    This course will teach you the fundamental concepts you need to start building applications with Vue.js. Who Is This FREE Course For? complete beginners who want to be web developers experienced developers who want to explore advanced topics any coder who enjoys learning something exciting How Long Is the Course? This course is 4 hours 22 minutes long, and it’s split into 35 lessons in total. You’ll find it’s a great resource that you will come back to often. In this course, you’ll learn why Vue.js is a great choice for a front-end framework, and you’ll discover how to use it in detail. You’ll start with building the simplest Vue components and learning to use core features like data binding, props, events, and computed properties. Then you’ll build that knowledge step by step with practical projects learning how to use the Vue CLI, forms, watchers, and custom events. You’ll also master key concepts like the Vue router and the Composition API. By the end of this course, you’ll be confident in using Vue.js for all your front-end development projects. What You’ll Learn fundamentals of Vue with no build tools or toolchains  create applications, define and use options, organize applications into components  learn the toolchains how to load and work with reactive data  how to handle user input and create custom events  manipulate style, create computed properties define objects that watch your data for changes  how to create single-page applications using the Vue router how to use the Composing API  Vue.js With no Tool-Chain Using the Vue CLI Working With Data Creating and Using Custom Events Using Vue Router Using the Composition API Follow Along, Learn by Doing I encourage you to follow along with this course, and you’ll learn about all the most important features of Vue.js To help, the Vue.js Tutorial: Beginner to Front-End Developer GitHub repository contains the source code for each lesson and the completed sample project that was built throughout the course.  1. What You Will Learn  Watch video lesson [0:00:00] ↗ Get an introduction to the course and an overview of what you’ll be building. 2. Vue.js With no Tool-Chain Getting Started With Vue Watch video lesson [0:02:31] ↗ Vue.js is the most approachable UI framework, especially without using any tool-chains. Vue.js CDN Link Visual Studio Code Here is the complete source code for a minimal, no-toolchain-required Vue.js hello world app. 1 <!DOCTYPE html> 2 <html lang=”en”> 3 <head> 4 <meta charset=”UTF-8″> 5 <meta http-equiv=”X-UA-Compatible” content=”IE=edge”> 6 <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> 7 <title>Vue Basics</title> 8 <link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css” rel=”stylesheet”> 9 <script src=”https://unpkg.com/vue@3″></script> 10 </head> 11 <body> 12 <div id=”content” class=”container”> 13 <h1>{{ pageTitle }}</h1> 14 <p>{{ content }}</p> 15 </div> 16 17 <script> 18 Vue.createApp({ 19 data() { 20 return { 21 pageTitle: ‘Hello, Vue’, 22 content: ‘Welcome to the wonderful world of Vue’ 23 }; 24 } 25 }).mount(‘#content’); 26 </script> 27 </body> 28 </html> Using Loops to Generate Content Watch video lesson [0:10:51] ↗ Collections are some of the most common types of data you will work with within your application. In this lesson, you’ll learn how to use the v-for directive to loop over collections to generate output. Binding Data to Attributes Watch video lesson [0:17:00] ↗ Data binding automatically keeps your components up to date with the underlying application data. See how it works in this lesson. Here’s an example of binding to data inside a loop. 1 <ul> 2 <li v-for=”(link, index) in links”> 3 <a 4 :href=”link.url” 5 >{{ link.text }}</a> 6 </li> 7 </ul> Setting Up Events Watch video lesson [0:25:11] ↗ Events are the lifeblood of any graphical application. You’ll learn how to listen for DOM events in this lesson. Binding CSS Classes I Watch video lesson [0:33:15] ↗ Manipulating CSS is key to providing dynamic and enhanced user experiences. You’ll learn how to bind CSS classes to state in this lesson. Using Computed Properties Watch video lesson [0:41:48] ↗ Sometimes you need to compute data on-the-fly in order to provide reactivity to your application. Computed properties give you that ability. Binding CSS Classes II Watch video lesson [0:48:05] ↗ There’s more than one way to skin a cat… err bind CSS classes. You’ll learn how to use arrays to do so in this lesson. Introducing Components Watch video lesson [0:55:00] ↗ Components help us organize our applications into smaller, maintainable pieces. Understanding Data Flow Watch video lesson [01:04:19] ↗ Components provide data to their children via props, and you’ll need to understand how that data flows in order to build your applications. Here’s a snippet that shows how to create and register a new component with Vue. 1 app.component(‘page-viewer’, { 2 props: [‘page’], 3 template: ` 4 <div class=”container”> 5 <h1>{{page.pageTitle}}</h1> 6 <p>{{page.content}}</p> 7 </div> 8 ` 9 }); 3. Using the Vue CLI Getting Started With the Vue CLI Watch video lesson [1:13:00] ↗ The Vue CLI makes it easy to get up and running with a full-blown project. You’ll install the CLI and create a project in this lesson. Current recommendations are to use create-vue with the Vite tooling for new Vue projects. vue-cli is in maintenance mode, but still works for creating Webpack-powered Vue apps like in this course. Starting a Project From Scratch Watch video lesson [1:21:30] ↗ We’ll delete most of that fresh new project we created in order to start completely from scratch. It’s good to practice these things! Applying CSS to Components Watch video lesson [1:32:18] ↗ Our applications are broken into smaller components, and those components need CSS. You’ll learn how to provide CSS to your application and components. 4. Working With Data Using the created() Lifecycle Event to Load Data Watch video lesson [1:41:51] ↗ The created() lifecycle event works a lot like the browser’s load event. It’s a great time to fetch data and supply it to your component before it’s rendered in the browser. Here’s an example of using the created lifecycle event to load page data from a remote server. 1 export default { 2 //… 3 4 created() { 5 this.getPages(); 6 }, 7 data() { 8 return { 9 pages: [] 10 }; 11 }, 12 methods: { 13 async getPages() { 14 let res = await fetch(‘pages.json’); 15 let data = await res.json(); 16 this.pages = data; 17 } 18 } 19 } Working With Unset Props Watch video lesson [1:48:19] ↗ Sometimes our components are ready and available before they have data to work with. You’ll learn how to handle those situations in this lesson. Deciding When to Load Data Watch video lesson [1:55:19] ↗ Some components depend upon their parent for data; others are independent and load their own. There are no hard and fast rules, so I’ll show you some strategies for loading data. Working With Forms Watch video lesson [2:01:14] ↗ The primary way we work with user input is via forms. Vue makes it laughably easy to work with forms and their data. Validating Forms Watch video lesson [2:08:43] ↗ Did I mention Vue makes it easy to work with forms? That includes validation. Updating and Filtering Data Watch video lesson [2:14:39] ↗ Vue gives us the tools to get/provide data that our components need in order to function. That includes updating and filtering data. Using Watchers Watch video lesson [2:21:05] ↗ Watchers give us the ability to watch certain properties and react when their values change. 5. Creating and Using Custom Events Creating Custom Events Watch video lesson [2:25:19] ↗ Vue makes it easy to create custom events. You’ll learn how in this lesson. Writing a Global Event Bus Watch video lesson [2:32:48] ↗ Unfortunately, custom events don’t bubble, which makes it difficult for parent components to listen to events of children nested deep in the tree. Thankfully, we can create our own global event bus. 6. Using Vue Router Introducing Vue Router Watch video lesson [2:44:37] ↗ The Vue Router makes it possible to „navigate” between components… kind of like pages. You’ll get the rundown in this lesson. Here is a simple router with a couple of static routes. 1 const router = createRouter({ 2 history: createWebHashHistory(), 3 routes: [ 4 { path: ‘/’, component: PageViewer }, 5 { path: ‘/create’, component: CreatePage } 6 ] 7 }); Using Route Params Watch video lesson [2:53:19] ↗ Components that handle routes don’t get their data via props because they don’t really have a parent. Instead, they rely on data from the URL via route params. You’ll learn how to use them in this lesson. Loading Data for Views Watch video lesson [2:59:18] ↗ Because views don’t get data from their non-existent parent, data has to be loaded from somewhere. A centralized data store could be your solution, and we’ll build one in this lesson. Watching Params to Reload Data Watch video lesson [3:10:07] ↗ If we try to „navigate” to a view that is already loaded by the router, we have to reload the data for the new route. You’ll learn how in this lesson. Using the Router’s Active Class Watch video lesson [3:16:57] ↗ The router keeps track of the currently active link. You’ll learn how to use it in this lesson (and clean up a lot of code!). Nesting Routes Watch video lesson [3:23:36] ↗ Routes, like components, can be nested. You’ll learn how and why you might want to do so in this lesson.  Here’s an updated router with params and nested routes. 1 const router = createRouter({ 2 history: createWebHashHistory(), 3 routes: [ 4 { path: ‘/:index?’, component: PageViewer, props: true }, 5 { 6 path: ‘/pages’, 7 component: Pages, 8 children: [ 9 { path: ”, component: PagesList }, 10 { path: ‘create’, component: CreatePage } 11 ] 12 }, 13 ] 14 }); 15 7. Using the Composition API Introducing the Composition API Watch video lesson [3:30:52] ↗ The Composition API was created to improve the organization of your component’s code. I’ll run over the basics in this lesson. Providing and Injecting Dependencies Into Components Watch video lesson [3:40:26] ↗ „Setup” components don’t use this, and it complicates how we get to our global properties. Instead, we’ll use Vue’s provide and inject features to access our global objects. Accessing Props and Router Functions Watch video lesson [3:48:18] ↗ The Composition API changes how we access… everything, including props and the route/router. You’ll learn how to access those in this lesson. Binding Data and Working With Forms Watch video lesson [3:54:58] ↗ In this lesson, you’ll learn how to bind data to forms in setup components. It’s easy. Defining Computed and Watched Values Watch video lesson [4:06:00] ↗ You can define computed and watched values in setup components. You’ll learn how in this lesson. Implementing the Delete Functionality Watch video lesson [4:16:18] ↗ We’ll finish off the management UI by providing delete functionality. Conclusion Watch video lesson [4:20:42] ↗ Vue.js is my favorite UI framework. And don’t get me wrong—React, Angular, and all of the other frameworks do their job just fine. But there’s something different about Vue. It’s very easy to get started, and it lacks a lot of the wonky rules that seem to plague other frameworks. It’s my hope that by now, you have a firm grasp of Vue’s fundamentals, and I hope you continue to use it in your current and future projects. Learn More  Learn more in the official Vue Documentation or The Vue Community Portal. Create Modern Vue Apps Using Create-Vue and Vite Jacob Jackson 16 Oct 2022 Boost Your Vue.js Workflow With Vue CLI 3 Ivaylo Gerchev 24 Sep 2022 Vue Plugins and Templates  CodeCanyon, Envato Elements, and ThemeForest are fantastic sources for Vue plugins and templates. They can help you save time, cut down on development costs, and deliver projects on time. Vue Admin Templates on ThemeForest Vue Plugins on CodeCanyon Vue WebTemplates on Envato Elements Vuzaz: Vue Minimal eCommerce Shopify Theme

  • Read and Create Cookies in JavaScript
    by Monty Shokeen on 31 ianuarie 2023 at 1:54

    Even if you haven’t used cookies before, you are probably already familiar with them. Almost every website that you visit asks to accept cookies. So, what are cookies? Cookies are basically small pieces of text that contain some information relevant to you or the website you are visiting. This information is stored in your browser and allows websites to give you a personalized experience, grant access to protected sections of the website, or gather analytics data. In this tutorial, I will show you how to manage cookies with JavaScript. Reading Cookie Information in JavaScript The Document interface contains a property called cookie that you use to read and write cookies. Simply using document.cookie will give you back a string that contains all your cookies separated by a semicolon. The following example shows all the cookies that are set on my browser for the Wikipedia homepage. 1 let all_cookies = document.cookie; 2 3 console.log(all_cookies); 4 /* Outputs: 5 GeoIP=IN:State_Code:State:My_Latitude:My_Longitude:v4; enwikiwmE-sessionTickLastTickTime=1675054195383; enwikiwmE-sessionTickTickCount=1; enwikimwuser-sessionId=7ed98fe7399e516cff54 6 */ I closed the page and then reopened it later. After a couple of refreshes and some waiting time, the value stored in the cookies had changed to the following: 1 let all_cookies = document.cookie; 2 3 console.log(all_cookies); 4 /* Outputs: 5 GeoIP=IN:State_Code:State:My_Latitude:My_Longitude:v4; enwikimwuser-sessionId=7ed98fe7399e516cff54; enwikiwmE-sessionTickLastTickTime=1675058494564; enwikiwmE-sessionTickTickCount=16 6 */ As you can see, the values in cookies can change over time. Websites can use them to track things like how long I spent on a page. The value returned by document.cookie shows that we only get back the name and value of cookies stored in the browser. Let’s write a JavaScript function that will give us the value of a stored cookie once we pass its name. 1 function read_cookie(name) { 2 let all_cookies = document.cookie.split(„; „); 3 let cookie_name = name + „=”; 4 5 for (let i = 0; i < all_cookies.length; i++) { 6 let clean_cookie = all_cookies[i]; 7 if (clean_cookie.startsWith(cookie_name)) { 8 return clean_cookie.substring(cookie_name.length, clean_cookie.length); 9 } 10 } 11 } There are currently four cookies on Wikipedia that I can access using JavaScript. I used our read_cookie() function to get the values from all of them. The value of the GeoIP cookie shows the location to be New York because it is masked by my VPN. You can try using the above function on Wikipedia or any other website to retrieve cookie values: 1 let geo_ip = read_cookie(„GeoIP”); 2 // Outputs: US:NY:New_York:40.74:-73.99:v4 3 4 let session_id = read_cookie(„enwikimwuser-sessionId”); 5 // Outputs: 398c37df147f0b377825 Creating Cookies in JavaScript You can also create a new cookie by using the cookie property and setting its value to a string that has the form key=value. The key here is the name of the cookie, and value is the value that you have set for the cookie. These are the only required values for creating a cookie, but you can also pass down other important information. To see how setting a cookie value works, you can visit https://code.tutsplus.com/tutorials and then open the browser console to execute the following code: 1 document.cookie = „site_theme=christmas”; Setting Expiration Time Unless specified otherwise, cookies you set are designed to expire at the end of a browsing session when users close the browser. If you want your cookie to expire at a specific time in the future, you should set an expires date by adding the following string to your cookie. 1 ;expires:GMT-string-fromat-date Our site_theme cookie above is set to expire as soon as your close the browser. You can verify this by closing the browser and then trying to read the cookie using the read_cookie() function we wrote above. We can extend its life by using the following code snippet: 1 document.cookie = „site_theme=christmas;expires=Thu, 28 Dec 2023 08:58:01 GMT”; 2 // The cookie will now expire on Thu, 28 Dec 2023 08:58:01 GMT The cookie will now expire on 28 Dec 2023. Try closing the browser window and reopening the page again to see that the cookie is still available for you to read. Another way to set the cookie expiration time is by using the following string: 1 ;max-age=cookie-age-in-seconds Let’s say you want the cookie to expire a week after it has been set. You can determine the number of seconds by calculating 60*60*24*7. The following line will set the cookie for you: 1 document.cookie = `site_theme=christmas;max-age=${60*60*24*7}`; 2 // The cookie will now expire one week from now You can set the expires value when you want the cookie to expire at a specific time, and the max-age value when you want the cookie to expire after a specific period. Setting the Domain and Path It is important to remember that you cannot set cookies for any third-party domain that you want. For example, a script running on tutsplus.com cannot set a cookie for wikipedia.org. This is done as a security measure. You can have even more control over the accessibility of a cookie by setting its domain and path values. You can set these two values by using the following string: 1 ;domain=domain;path=path The domain is set to the host of the current location by default. Since we created our earlier cookies by opening the browser console on https://code.tutsplus.com/tutorials, our cookie is also accessible only on the code.tutsplus.com subdomain. Try using the read_cookie() function on the browser console for https://design.tutsplus.com/tutorials, and it will be undefined. You can create a cookie that is accessible on all subdomains of tutsplus.com by executing the following line: 1 document.cookie = „site_theme=christmas;expires=Thu, 28 Dec 2023 08:58:01 GMT;domain=tutsplus.com”; Similarly, you can also provide a path for which the cookie will be accessible. Let’s say you want the site_theme cookie to be available only on the URLs that contain /tutorials in their path. You can do so with the following line: 1 document.cookie = „site_theme=christmas;expires=Thu, 28 Dec 2023 08:58:01 GMT;domain=tutsplus.com;path=/tutorials”; After executing the above line, the cookie won’t be accessible on the URL https://code.tutsplus.com/categories/javascript because of the path restriction. Modifying and Deleting Cookies in JavaScript When we were reading cookie information from Wikipedia at the beginning of this tutorial, you might have noticed that the value of the cookie enwikiwmE-sessionTickTickCount was updating with the passage of time. There are a variety of reasons why you might want to update the value of a cookie periodically, such as counting the number of visits or updating user preferences. Once you know the basics of creating cookies, you will also be able to easily modify existing cookies. Continuing our example from the previous section, let’s say you want to change the value of the site_theme cookie to new_year and change the expiration date to the new year as well. You can do so with the following code: 1 document.cookie = „site_theme=new_year;expires=Mon, 1 Jan 2024 08:58:01 GMT;domain=tutsplus.com;path=/tutorials”; Do you remember when I said that we can specify when a cookie expires by passing the expires or max-age values? We can also use them to delete a cookie. Setting the value of max-age to 0 will make the cookie expire in the next 0 seconds, or in other words now. Similarly, you can also set the value of expires to a date in the past, and it will clear the cookie. 1 document.cookie = „site_theme=new_year;max-age=0;domain=tutsplus.com;path=/tutorials”; 2 document.cookie = „site_theme=new_year;expires=Mon, 1 Jan 2001 08:58:01 GMT;domain=tutsplus.com;path=/tutorials”; Both the lines above will work if you want to delete a cookie. One important thing to remember when you are modifying or deleting cookies is that the domain and path values have to match the cookie that you are modifying or deleting. Final Thoughts In this tutorial, we learned how to manage cookies in JavaScript. You should now be able to read data from cookies, create new cookies, and modify or delete existing cookies. While cookies are great for storing information, there are a few things to be kept in mind. First, cookie storage is limited to about 4 kB, so you shouldn’t be using them to store a large amount of information. Second, you also cannot create a large number of cookies for the same domain. The limit varies across browsers and is fairly generous at around 300 at least. This should generally be sufficient. If you are looking to store a large amount of data and only want to access it locally, you might consider using either Local Storage or Session Storage. Local Storage and Session Storage in JavaScript Monty Shokeen 19 Jan 2023

  • How to Build a REST API With Laravel
    by Franc Lucas on 30 ianuarie 2023 at 3:57

    Laravel lets you easily and quickly build RESTful APIs. This could be the back-end to a front-end web app, a data source for a mobile app, or a service for other apps or APIs. There are a lot of moving pieces to coding a RESTful API, but Laravel makes it a lot easier. In this free course, you’ll learn everything you need to know to build RESTful APIs with Laravel. What You’ll Learn define data models and seeding database test data handle basic GET requests  transform data from the database into a consistent and conventional JSON format create flexible and reusable filter syntax for users to query and filter data handle and validate POST, PUT, and PATCH requests implement bulk inserts for end users to quickly insert multiple entities with a single request  protect your API endpoints with Laravel Sanctum to authenticate and authorize requests Who Is This Free Course For? complete beginners who want to be web developers experienced developers who want to explore advanced topics programming enthusiasts who enjoy learning something exciting Getting Started Providing Data Manipulating Data Authentication Follow Along, Learn by Doing I encourage you to follow along with this course, and you’ll learn about all the most important features of Vue.js To help, the Build a Rest API With Laravel Github repository contains the source code for each lesson and the completed sample project that was built throughout the course.  1. Introduction Watch video lesson [0:00:00] ↗ This course will teach you how to build a Rest API with Laravel. In this introductory lesson, you’ll take a look at the scope of the course.  2. Getting Started Creating the Project Watch video lesson [0:01:38] ↗ In this lesson, you’ll go over the things you’ll need to follow along in this course. Follow along to set up your dev environment and create your project. Homebrew XAMPP Composer Postman Here is a quick tutorial on how to set up your Laravel environment for Windows: How to Install Laravel on Windows Franc Lucas 30 Nov 2022 Designing and Seeding the Database Watch video lesson [0:7:36] ↗ In this lesson, you’ll create the migrations, factories, and seed data for our database. 3. Providing Data Versioning and Defining Routes Watch video lesson [0:19:22] ↗ Good web APIs are versioned, so you need to implement some kind of versioning. You’ll also set up the routes for the first version of the API. Transforming Database Data Into JSON Watch video lesson [0:26:17] ↗ RESTful APIs typically provide data in JSON format using JSON naming conventions. In this lesson, you’ll use Resource classes to transform our data into conventional JSON. Filtering Data Watch video lesson [0:35:48] ↗ You need to provide the ability for clients to filter results. You’ll implement a customer filter in this lesson. Filtering More Data Watch video lesson [0:49:47] ↗ In this lesson, you generalize our filter functionality so that you can reuse it for any resource. Including Related Data Watch video lesson [0:58:49] ↗ It sometimes makes sense to include related data in the API’s results, but it should be a feature that clients opt in to. You’ll implement that in this lesson. 4. Manipulating Data Creating Resources With POST Requests Watch video lesson [1:05:37] ↗ POST requests are for creating resources. You’ll handle POST requests to create customer resources in this lesson. See the Laravel documentation on Built-in Validation Rules for more information. Updating With PUT and PATCH Watch video lesson [1:14:48] ↗ We update data using PUT and PATCH requests, and you’ll learn how to handle both types of requests in this lesson. Implementing Bulk Insert Watch video lesson [1:22:51] ↗ Some resources need to be inserted in bulk. You’ll learn how to implement that in this lesson. 5. Authentication Protecting Routes With Sanctum Watch video lesson [1:33:41] ↗ Laravel 7 introduced Sanctum, a token authentication scheme for APIs and SPA. It’s awesome, and you’ll use it to create tokens in this lesson. Learn more about Laravel Sanctum in the official docs. Authorizing Requests With Token Abilities Watch video lesson [1:41:29] ↗ Sanctum allows us to assign abilities to tokens, and it’s easy to authorize requests. However, there’s a caveat that you’ll learn about in this lesson. How to Create a Custom Authentication Guard in Laravel Sajal Soni 31 Mar 2022 Conclusion Watch video lesson [1:48:10] ↗ Laravel has the tools we need to build usable and scalable applications—including RESTful APIs. In fact, Laravel does a lot of the hard stuff for us, making it a much more enjoyable way to build software. Learn more in the official Laravel Documentation or The Laravel Community Portal. Learn Laravel Franc Lucas 22 Oct 2022 Building Web Applications From Scratch With Laravel Kingsley Ubah 22 Jun 2022 FREE 7.1 Hours PHP Tutorial for Beginners – Full Course | OVER 7 HOURS! Learn the fundamentals of PHP and object-oriented programming in this free 7-hour PHP tutorial. Jeremy McPeak will help you learn PHP and use it to write web apps. 

  • Best Ways to Preload Images Using JavaScript, CSS, and HTML
    by Monty Shokeen on 30 ianuarie 2023 at 2:50

    One of the most important things that you can do to improve the user experience on your website is to make sure that people don’t spend their time waiting for an image or other element to load. How quickly a webpage and all its contents load depends on a large number of factors, and some of them will be beyond your control. However, we should try our best as web developers to make the browsing experience as seamless as possible. In this tutorial, I will show you different techniques to preload images on a webpage for a smooth user experience. The Need for Preloading Images We will begin the tutorial by first discussing why you might need to preload images. Let’s say you are building a portfolio website for a real estate agent where they can showcase houses for sale. The agent wants you to show a list of houses with an image of the exterior of the houses. They also want you to design the page in such a way that hovering over a house image loads another image of the interior of the house, with a link to see all other images. The problem here is that the image of the interior of the house will only start loading when users hover over the image. This means that they will not see any image for a few moments after the initial hover event, depending on their internet speed. You can see this problem in the following CodePen demo: Preloading the images will avoid this delay in image load on hover. Also, some large images might take a while to load, so it is better to preload them for a better user experience. Preloading Images Using HTML You’re probably already familiar with the link tag in HTML. We generally use it to load an external CSS stylesheet, but you can also use it to load other types of resources as well. There are two important attributes of the link tag: the href attribute, which is used to provide the path to the resource that we want to fetch the rel attribute, which specifies the relationship of the resource with the containing document With a CSS stylesheet, the link tag looks like this: 1 <link rel=”stylesheet” href=”navigation.css” /> The rel attribute can take a lot of valid values. One of them is preload, which we will use to preload our images. The preload attribute tells the browser to preemptively fetch and cache the linked resource as it will be needed on the current page. You also need the as attribute when the value of the rel attribute is set to preload. This will specify the type of content that is being loaded by the link tag. This attribute serves many important purposes, such as applying the correct content security policy, prioritization of the request, etc. Skipping it could prevent your image from being preloaded. We will load our image in the following div element: 1 <div class=”hover-me”></div> Then apply the following CSS to the div element. As you can see, the background image URL changes whenever someone hovers over the div element. 1 div.hover-me { 2 width: 640px; 3 height: 360px; 4 background: url(„https://picsum.photos/id/128/1920/1080”); 5 background-size: contain; 6 cursor: pointer; 7 margin: 0 auto; 8 position: relative; 9 } 10 11 div.hover-me::before { 12 content: „Lake”; 13 background: black; 14 color: white; 15 position: absolute; 16 top: 0.75rem; 17 left: 1rem; 18 padding: 0.5rem; 19 font-size: 1.5rem; 20 border-radius: 5px; 21 } 22 23 div.hover-me:hover { 24 background: url(„https://picsum.photos/id/296/1920/1080”); 25 background-size: contain; 26 } 27 28 div.hover-me:hover::before { 29 content: „Mountains”; 30 } The image that shows up when we hover over the div element is preloaded by using the following markup. You should ideally place the link tag inside the head tag of your webpage. 1 <link rel=”preload” as=”image” href=”https://picsum.photos/id/296/1920/1080″ /> The following CodePen demo shows the image preloading in action: Preloading Images Using CSS You might have noticed in the previous section that both the images we used were actually applied as a background to the div element. However, only one of them was downloaded by the browser. The image that was applied as background on hover was downloaded only after the hover event occurred. In the previous section, we forced the hover image to download with the help of HTML. However, we could also trick the browser into downloading the hover image by applying it as a background image to another element on the webpage. Another option involves setting the image URL as a value of the content property. I prefer to use the body element along with the ::before or ::after pseudo-elements. The URLs that I want to download will be set as a value of the content property of any of the pseudo-elements. One important thing to keep in mind here is that we need to push the pseudo-elements far off the screen to prevent their contents from accidentally appearing on the screen. The following CSS takes care of all this for us: 1 body::before { 2 content: url(„https://picsum.photos/id/296/1920/1080”); 3 position: absolute; 4 top: -9999rem; 5 left: -9999rem; 6 opacity: 0; 7 } I have also set the opacity to 0 as a precautionary measure. Do keep in mind that you shouldn’t set the display property to none to hide the element. In that case, the browser is much more likely not to download the image at all. You can see that the image we need on hover is preloaded in the following CodePen demo: Preloading Images Using JavaScript It is also possible to preload images using JavaScript. This method gives you the most control over the way you preload the images. Preloading images using JavaScript is also more convenient in situations where you have to load a large number of images. However, it will not work if JavaScript execution is disabled in the browser. The following function can help us preload any image in JavaScript. 1 function preload_image(im_url) { 2 let img = new Image(); 3 img.src = im_url; 4 } The function accepts the path to an image you want to preload as a parameter. Inside the function, we use the image constructor to create a new instance of HTMLImageElement. After creating the image element instance, we set the value of its src property to the path of the image we want to preload. All that’s needed now is a call to the preload_image() function, as shown below: 1 preload_image(„https://picsum.photos/id/296/1920/1080”); You can see the JavaScript image preloading in action in the following CodePen demo: Final Thoughts In this tutorial, we learned about three different techniques to preload images. Using the link tag in HTML allows us to start loading images as early as possible. On the other hand, it is much more convenient to use JavaScript when you want to preload multiple images. You can also control the order in which images are preloaded with JavaScript. This way, we can make sure that image preloading doesn’t block the main content from loading first.