Categories
Beginner

Proper use of Arrays with UrlSearchParams

If you’re executing ‘get’ requests directly, you may sometimes need to send in an array of data. Below is an example of how to build the query string correctly using UrlSearchParamsmethod append:

var url = new URL(url ) // url is some url string

let searchParams =  new URLSearchParams({}); // you can pass in any initial data that you'd like here
let posts = get_my_post_array(); // returns an array of post ids
for(let post of posts){
    searchParams.append("post[]",post); // this is what 
    you need. Notice the square   brackets
}
url.search = searchParams.toString();
let json = fetch(url).then(response => response.json()); // and get the response

Now your back-end server will receive an array “post” with all the required Ids!

Thoughts? Comments? Let me know below.

Categories
Beginner

Sticky Headers with CSS and HTML

Hey Guys!! I wanted to see if I can extend this tutorial from w3schools. What they show here is how to create a sticky header that scrolls down with the top of the page. My goal here is to check if we require any javascript for this at all. I’m looking for this particular appearance. Notice that the first statement “I come before the rest” is visible at all times when it’s in the viewport.

So first, the HTML:

<h3>I come before the rest</h3>
<div class="header sticky" id="myHeader">
      <h2>My Header</h2>
</div>
<div class="content">
      <h3>On Scroll Sticky Header</h3>
      <p>
        The header will stick to the top when you reach 
        its scroll position.
      </p>
      <p>Scroll back up to remove the sticky effect.</p>
      <p>
        Some text to enable scrolling: “Lorem ipsum dolor 
        sit amet, illum definitiones no quo, maluisset 
        concludaturque et eum, altera fabulas ut quo. 
        Atqui causae gloriatur ius te, id agam omnis 
        evertitur eum. Affert laboramus repudiandae nec 
        et. Inciderint efficiantur his ad. Eum no
        molestiae voluptatibus”.
     </p>
 <!-- Many more of these paragraphs -->
 
   </div>

Secondly, the CSS:

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}
 
.content {
  padding-top: 102px;
}
 
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

But there seems to be a problem, the statement on the top is hidden behind the header. That is because we used ‘fixed’ for the header position. Luckily, there is a very simple solution. Instead of using ‘fixed’ for the position, I will use ‘sticky’:

.sticky {
  position: sticky;
  top: 0;
  width: 100%;
}

Sticky will basically tell the browser to fix the header position only when it needs to (At the point of exiting the viewport). This way, the h3 header is now in its correct place and we’re done.

Thoughts? Comments? Let me know below!

Categories
Beginner

How to Setup a JSON Server?

This is the pattern I’m using when working with the json-server. Of course, you will first need to install it. You’d probably want to install it globally with using this piece of code:

npm i -g json-server

Then I find that the best way to set up my Db is to separate it into two files.

First I create a ‘data.js’ file to contain all of my data. For example, say that our data is products. The data.js file needs to look like:

let db = { 
	"products" :[
		{ title: "Product 1",},
		{ title: "Product 2",},
		{ title: "Product 3",},
		{ title: "Product 4",},
		{ title: "Product 5",},
		{ title: "Product 6",},
		{ title: "Product 7",},
		{ title: "Product 8",},
		{ title: "Product 9",}
	]
}
id = 1;
db.products.forEach(
	(product) => {
		product['id'] = id; id++; 
	}
);
module.exports = db;

Notice the module.export statement at the end. Additionally, I am adding Id’s to all of the products in a For loop (rather than setting it one-by-one), because json-server supports this field by default.

Then I require this module in db.js:

data = module.require("./data.js");
module.exports = () => data;

It’s more convenient for me to use two files, but we can probably store everything in db.js.

Finally, I will execute the json-server using the following piece of code:

json-server db/db.js --delay 2000

I’m also adding some delay to simulate actual server communication.

Json-server is a very cool tool that you can do a lot of stuff with. Comment below if you’ll have any issues or suggestions.

Categories
Beginner

Loading Animation with Fade Transition (Using Svelte)

Check out this cool animation block for Svelte. I’m fetching something from a random remote API as shown below. Notice that you need to chain two Promises using then to get the JSON response:

loading = fetch("http://localhost:3000/products").
then(response => response.json());

Then I will use the loading Promise with an async block:

{#await loading}       
	<div class="spinner-border" role="status">            
    		<span class="sr-only"></span>      
	</div>    
{:then results}        
	<div transition:fade> 
    		// display the result somehow       
	</div>    
{:catch error}       
	<p style="color: red">
		{error.message} // show an error 
	</p>  
{/await} 

What I’m doing is showing the loading animation until the result comes in, then I use fading animation to show the result. I’m also using catch to display error for the worst-case scenario. 

That’s it! If there is a better way to do this please let me know in the comments section.

Categories
Beginner

Basic PHP Tutorial (Part 03)

Functions in PHP

  • Always starts with the keyword function.
function func_with_no_parameters(){
    echo "here";
}
func_with_no_parameters(); // prints here
  • Can receive parameters
function func_with_parameters($x, $y){
    echo $x * $y;
}
func_with_parameters(2, 3); // prints 6
  • Can have return statements
function func_with_parameters($x, $y){
    if($x==2){
        return;
    }
    echo $x * $y;
}
func_with_parameters(2, 3); // prints 6?
function func_with_parameters($x, $y){
    return $x * $y;
}
echo func_with_parameters(2, 3); // prints 6

Include Files

  • Sometimes you write your code in separate files.
  • Then you need to include your other files.
include "some_other_file.php"; // includes some_other_file.php
include "some_folder/some_other_file.php"; // includes from sub folder some_folder

// what if the files both include eachother (circular dependency)?
  • Don’t create circular dependency (two files including each other).
  • Use require_once to raise an error if the file is not found.
require_once "some_other_file.php"; // require once some_other_file.php

Multi Line Comments

/**
 * this is the syntax for multi line comments
 * second line.
 * third line.
 */

Errors

  • Errors can occur
  • Read the error to know where it happened
  • Most common errors – Syntax errors.
 //missing semicolon
 $var = 1
 if(true{ //missing parenthesis
 }

Parse error: syntax error, unexpected ‘$var ‘ (T_VARIABLE) in C:\xampp\htdocs\simple\index.php on line 4.

Unidentified Function

<?php
undefined_function(); // calling a function that doesn't exist
?>

Fatal error: Uncaught Error: Call to undefined function undefined_function() in C:\xampp\htdocs\simple\undefined_function.php:3 Stack trace: #0 {main} thrown in C:\xampp\htdocs\simple\undefined_function.php on line 3

<?php

$x = $y; //what is $y?

?>

Notice: Undefined variable: y in C:\xampp\htdocs\simple\undefined_variable.php on line 3

Categories
Beginner

Basic PHP Tutorial (Part 02)

IF ELSE Statements

  • Examples of if else syntax
// what will be printed?
$var = true;
if($var){
    echo "var is true!";
}else{
    echo "var is false!";
}
  • “” is false
  • Empty array is false
  • 0 is false
// what will be printed?
$var = "";
if($var){
    echo "var is true!";
}else{
    echo "var is false!";
}

Arrays in PHP

  • A simple array
$arr = array("1", "2", "3"); // create an array
echo $arr[1]; // what will be printed?

$arr = ["1", "2", "3"]; // this is the same
echo $arr[1]; // the same!
  • In the above we created a simple array.
  • Remember: an array starts in index 0.
  • Therefore printing the index 1 of the array printed the second element.
$arr = ["1", "2", "3"];
echo $arr[1]; // prints 2
  • In PHP we can create arrays with keys. It’s very useful
$arr = ["key1" => "value1", "key2" => "value2"];
echo $arr['key1'];

Loops in PHP

For Loop…..

  • Notice the 3 components from left to right: starting the counter, checking some condition, increment the counter.
  • Notice the new line character \n
for ($x = 1; $x <= 10; $x++) {
    echo $x . "\n"; // prints 1 2 3 4 … 10 in separate lines 
}

For Each Loop…

  • On array by value
// for regular array
$arr = ["1", "2", "3"];
foreach($arr as $element){
    echo $element . "\n"; // prints 1 2 3 in separate lines
}

// for array with keys
$arr = ["key1" => "value1", "key2" => "value2"];
foreach($arr as $element){
    echo $element . "\n"; // prints value1, value2 in separate lines
}
  • On array by key and value.
$arr = ["key1" => "value1", "key2" => "value2"];
foreach($arr as $key => $element){
    echo $key . " " . $element . "\n"; // prints key1 value1, key value2 in seperate lines
}

Live Coding

  • Iterate over an array of strings and print all strings which are longer then 6 characters in a new line.
  • Now print only if they are longer then 6 and shorter then 10.

Categories
Beginner

Basic PHP Tutorial (Part 01)

Variables in PHP

No Typing

  • You can assign anything to a PHP variable (as opposed to java, for example)
  • Notice the dollar sign, each variable in PHP starts with a $ sign.
// variable with number
$var = 1; // ‘var’ can be anything
$var = 1.1;
// string
$var = "Hello world!";
// boolean
$var = false;
$var = true;

Strings

Strings are surrounded by quotes:

$var = "Hello"; // double quotes
echo $var; // Prints Hello

$var = 'Hello'; // single quote - the same
echo $var; // Prints Hello

$var = "Hello and 'Hello'"; // quotes in quotes
echo $var; // Prints Hello and 'Hello'

You can get the length of the string. Use strlen:

$var = "Hello";
echo strlen($var); // prints 5

$var = " Hello "; // spaces are characters too!
echo strlen($var); // prints 7

You can concatenate strings. Use the.operator:

$var = "Hello";
echo $var; // Prints Hello

$var = $var . " world!"; // concatenates the strings, notice the .
echo $var; // prints Hello world!

Boolean Operators

  • >,>=,<,<=,==,!=
// what will be printed?
$var1 = 2;
$var2 = 3;
if($var1 > $var2){
    echo "True!";
}else{
    echo "False!";
}
  • && – and
// what will be printed?
$var1 = "Hello";
$var2 = "world";
if(strlen($var1) == strlen($var2) && $var1!=$var2){
    echo "True!";
}else{
    echo "False!";
}
  • || – or
// what will be printed?
$var1 = "Hello";
$var2 = "world";
if(strlen($var1) < strlen($var2) || $var1==$var2){
    echo "True!";
}else{
    echo "False!";
}
  • ! – not
// what will be printed?
$var = "Hello";
if(!$var){
    echo "True!";
}else{
    echo "False!";
}

Categories
Beginner

How to set up Enviromental Vairables on Windows?

What are Enviromental Variables?

  • They are dynamic values
  • Existing in every operating system
  • Can be created, edited, saved and deleted
  • Change the way software / programs behave.

Search for ‘system enviroment variables’ using the windows search bar:

Afterwards, click on ‘Enviroment Varibales’:

Search for the ‘Path’ variable and click on ‘Edit’:

Afterwards, click ‘New’ to add any folder as you wish. Entire files in that folder will now be available in the command line:

Categories
Beginner

How to set up WP-CLI?

WPCLI (WordPress Command Line Interface) is the command-line interface for WordPress. You can update plugins, configure multisite installations and much more, without using a web browser.

Download the phar from https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar. Put it where you want.

add that directory to the environment variables

add a file called wp.bat within that directory with the following content:

@ECHO OFF
SET BIN_TARGET=%~dp0/./wp-cli.phar
php "%BIN_TARGET%" %*

Final step: in order to avoid using wp.bat on the command line put another file called wp (without any extension) in the same directory. In that file insert the following:

wp.bat $@

Thats it! now you can use the wp cli from anywhere. Tested on git bash and power shell on windows.

Categories
Beginner

WordPress Xampp (Tute 01)

Download and Install XAMPP

Installation

This tutorial was written for windows. Installation on Mac is similar.

  • Download Xampp from https://www.apachefriends.org/index.html (simply download the version for your operating system – currently 7.4.1)
  • In Windows, the default installation directory is C:\xampp
  • Click through the installation. The default parameters should be fine.

Activation

Once you have install Xampp activate it:

  • You should see:
  • Click start on the first two buttons from the top (Apache and MySQL).
  • Check that MySQL works by clicking Admin on (next to the stop button on the MySQL line).
  • Check that Apache works. Go to your favorite browser and enter the address localhost/dashboard
  • You’re finished!

Download WordPress

Install WordPress

  • Extract the contents of the file you downloaded to the htdocs directory in xampp (in windows C:\xampp\htdocs).
  • You should now have another folder in xampp called wordrpess.
  • Open phpmyadmin just like in step 3 of the Xampp installation.
  • Click Databases.
  • Create another database, I will call my database testsite (but you can use a different name). Make sure the collation field is utf8_general_ci.
  • Now, open your browser and go to localhost/wordpress.
  • You should see the wordpress installation screen.
  • Choose English. In the next screen press lets go.
  • Now, enter the database name to the name you selected in step 4 (I will use testsite). Choose a username and password for the database (you can use root for the username and an empty password). do not change the last two fields (Database host and table prefix).
  • Click run the installation.
  • Fill the required form.
  • Login and see that everything works

You have completed the installation!