Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
JavaScript

Intro to OOP in JavaScript

TL;DR

This post will not be a regular step by step post as I usually do it; this will rather be a collection of some notes from a recent lecture I did. However, I hope you still find it useful.

OOP – Object Oriented Programming

  • an object has a state (represented by properties) and a behavior (represented by methods)
  • functions on an object are called methods
  • a developer doesn’t need to know how an object’s methods work under the hood to be able to use them (encapsulation)
  • a lot of times it makes sense to model real-life objects as objects in the code

⚠️ interesting thing in JavaScript is that arrays are actually objects

You can test it like this: console.log(typeof []);

It’s an object because it has a property like length, and methods like pop and push

object literal

const person = {
    name: 'Nikola',
    age: 33,
    walk: function() {
        console.log("I'm walking");
    }
}

console.log(person.name);

There’s also this thing called ‘bracket notation’:

person['name']

person['walk']();

Here’s how you would output all of the object’s properties with jQuery:

$.each(person, function(i,o){
    console.log(i, o);
});

this in JavaScript

  • normal function calls
function f(){
    console.log(this); // Window object
}

f();
  • object methods
var obj = {
    a: "test",
    b: "test 2",
    log: function() {
        console.log(this.a);
    }
}

obj.log();
  • constructed object methods
var Person = function(name, surname) {
    this.name = name || 'Marko';
    this.surname = surname || 'Maric';

    this.log = function() {
        console.log(this.name + " " + this.surname);
    }
}

var pero = new Person('Pero', 'Peric'); // constructor function
pero.log();

JavaScript Class Syntax

Object literals fall short when you have to create multiple of them. Having to type each of them out and then in case of a change, change it in all the places would be unmanageable.

Class is basically a blueprint for objects that will be created with this blueprint. It contains some base set of properties and methods. The class syntax is new to JS in ES2015 and it’s actually something called ‘syntactic sugar’. It has the same functionality as the prototype syntax, and it’s actually still using prototypes under the hood.

class Pet {
    constructor(animal, age, bread, sound) {
        this.animal = animal;
        this.age = age;
        this.bread = bread;
        this.sound = sound;
    }

    speak() {
        console.log(this.sound);
    }
}

const djoni = new Pet('dog', 1, 'bulldog', 'vau vau');

console.log(djoni);

getters

class Pet {
    constructor(animal, age, bread, sound) {
        this.animal = animal;
        this.age = age;
        this.bread = bread;
        this.sound = sound;
    }

    get activity() {
        const today = new Date();
        const hour = t.getHours();

        if (hour > 8 && hour < 20) {
            return 'playing';
        }
        else {
            return 'sleeping';
        }
    }

    speak() {
        console.log(this.sound);
    }
}

const djoni = new Pet('dog', 1, 'bulldog', 'vau vau');

console.log(djoni.activity); // activity is a so-called 'computed property'.

setters

get owner() {
    return this._owner.
}

set owner(owner) { // MUST have exactly one formal parameter!
    this._owner = owner; // this is called a 'backing property'
}

djoni.owner = 'Nikola';
JavaScript

Making AJAX calls using the Fetch API

TL;DR

In this post we’ll do everything we did in the second post, but with Fetch API.

What’s this Fetch API?

The almighty docs say

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest (see the first post in the series on how to do that), but the new API provides a more powerful and flexible feature set.

I prepared this demo page so that you can test.

You’ll remember from the last post that in order to make an AJAX call with jQuery, you have to do something like this:

$('#result').load('http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');

Go ahead and run that code on the demo page in the browser’s dev tools Console (consult the last post if you’re stuck).

Now, the very same thing with the Fetch API looks like this:

fetch('http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola')
  .then(function(response) {
    return response.text();
  })
  .then(function(text) {
    $('#result').html(text);
  });

Go ahead and try it in the Console. Change the ime parameter, and you’ll see that the text on the page will change to Hello [name], where [name] will be the parameter you entered. Note that in the example above I still used jQuery to set the content of the div with id result.

The docs have way more info on this but, as they say, the difference between fetch() and $.ajax() is in two main things:

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  • By default, fetch() won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

⚠️ At a later point you may want to read a bit more about Promises in Javascript.

Rewriting the mini project

I encourage you to try it for yourself and then check your solution to mine.

The mini project (which you can test here) would be rewritten like this:

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
fetch(link)
    .then(function(response){
        return response.json()
    })
    .then(function(result){
        var oglasiHTML = '';
        $.each(result, function(index, oglas){
            var klasaCijene = '';
            if (oglas.cijena < 100){
                klasaCijene = 'is-success';
            }
            else if (oglas.cijena >= 100 && oglas.cijena < 300){
                klasaCijene = 'is-info';
            }
            else if (oglas.cijena >= 300){
                klasaCijene = 'is-danger';
            }

            oglasiHTML += `
                <div class="columns">
                    <div class="column is-one-quarter">
                        <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                    </div>
                    <div class="column">${oglas.tekst}</div>
                </div>
            `;
        });

        $('#oglasi').html(oglasiHTML);
    });

There are a few things that I’d like to point out here:

  • I used the response.json() because I know that this API returns a JSON response (you can check by opening that link in the browser).
  • I used the jQuery each function to iterate over the result.
  • I used the template literals to construct the final oglasiHTML in a much cleaner way than we did that in the previous post with using concatenation.

I want more examples

Say you have this demo page, and you need to make the newsletter signup form use AJAX instead of going to a new page when you click the Subscribe button. Right now the API (located at http://nikola-breznjak.com/_testings/ajax/email.php) doesn’t actually process what you send to it but try to send data with the request as well for practice.

How would you do it? Where would you start?

Well, here are a few search terms you could Google:

  • `fetch api submit data’

Again, here’s my solution, but I encourage you to try it yourself first.

$('form').submit(function(ev){
    ev.preventDefault();
    var url = $(this).attr('action');
    var formData = $(this).serialize();
    fetch(url, {method: 'post', body: formData})
        .then(function(response){
            $('#newsletter').html('Thank you for subscribing, please check your email.');
        });
});

There are a few things that I’d like to point out here:

  • I was able to use the form selector without any id because it’s the only form on the page. If there were more forms on the page, I’d have to distinguish them by using an id (which is always a good practice, even if it’s just one form)
  • I used jQuery’s submit function to set an event handler that will be executed when the form will be submitted (Subscribe button clicked, or ENTER pressed while in one of the fields)
  • I used the ev.preventDefault() to prevent the form from “doing its thing” and loading the ’email.php’ page, as its default behavior
  • I used $(this).attr('action') to extract the API URL from the form definition it the HTML (feel free to check it out in the element inspector)
  • I used $(this).serialize() to encode a set of form elements as a string which I then passed to body attribute of the fetch settings object. This function sends a request to the server using the POST method (using the method setting on the settings object), which (as we learned in the previous post) is the preferred way of sending some sensitive data that needs to be handled on the server
  • I used the html function on a div with the id newsletter to set its new content

Can I have one more, please?

Sure, but promise you’ll do it yourself first!

I do ?

OK then, let’s do this ?

Here’s a new demo page that you’ll use for this example.

⚠️ I’m using Bulma to make the site look pretty. As their website says:
‘Bulma is a free, open-source CSS framework based on Flexbox and used by more than 150,000 developers.’
I’ll just say it’s really great and easy to learn, so make sure you check it out.

In this challenge, you have to create a gif search application using the Giphy Search API. As the docs state, you’ll need to get the API key by creating an app. Once you do that, you’ll be able to search their API like, for example, this: http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC. You can use this API key, but be sure to create your own if this one gets banned for too many requests ?‍

Once you fetch the gifs (or still images if you so choose), show them in the div with a class result (yes, class, not id ?).

Here’s the part where you roll up your sleeves, create it, feel proud of yourself ?, and then come here to check how I did it.

$('form').submit(function(ev){
    ev.preventDefault();
    var searchTerm = $('input').val();

    var apiLink = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=" + searchTerm;

    var output = '';
    fetch(apiLink)
        .then(function(response){
            return response.json();
        })
        .then(function(images){
            $.each(images.data, function(i, im){
                output += `<img src="${im.images.downsized.url}"/>`;
            });

            $('.result').html(output);
        });
});

As you may notice, very few things changed from the last post, and it’s quite easy to exchange the jQuery AJAX calls with Fetch API.

Conclusion

That’s all for this blog post. I hope it was useful and that you’ve seen how easy it is to make AJAX requests with the Fetch API. I also hope you liked the demo exercises ?
This wraps it up with these three post series. Have a great time and see you soon! ?

Books

Way of the Warrior Kid – Jocko Willink

Here are my favorite quotes from the book Way of the Warrior Kid: From Wimpy to Warrior the Navy SEAL Way: A Novel by Jocko Willink:

If you need rest, you go to sleep earlier. You don’t sleep in, and you don’t miss workouts. Even if you can’t perform at a high-level, showing up and doing something is still a thousand times better than not showing up at all.

The most important part of discipline is following rules that you set for yourself. It is doing things you might not always feel like doing – things that make you better.

I don’t worry about motivation, because motivation comes and goes. It’s just a feeling. You might feel motivated to do something, and you might not. The thing that keeps you on course and keeps you on the warrior path isn’t motivation. It is discipline. Discipline gets you out of bed. Discipline gets you onto the pull-up bar. Discipline gets you to grind it out in the jiu-jitsu class.

We don’t quit. Ever.

Fear is normal. In fact, fear is good. Fear is what warns you when things are dangerous. Fear is what makes you prepare. Fear keeps us out of a lot of trouble. So there is nothing wrong with fear. But fear can also be overwhelming. It can be unreasonable. It can cause you to freeze up and make bad decisions or hesitate when you need to act. So you have to learn to control fear. And that’s what you need to do right now.

The fear is in the waiting. Once you have prepared, trained, studied and planned, there is only one thing left to do: go.

You know the path. And you are humble. That is the most important thing about being a leader.

JavaScript

Making AJAX calls using jQuery

TL;DR

In this post we’ll do everything (and a bit more ?) we did in the first post, but with jQuery.

Why is jQuery better?

I prepared this demo page so that you can test.

You’ll remember from the last post that in order to make an AJAX call in pure JavaScript, you have to do something like this:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4){
        document.getElementById('result').innerHTML = xhr.responseText;
    }
};
xhr.open('GET', 'http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');
xhr.send();

Go ahead and run that code on the demo page in the browser’s dev tools Console (consult the last post if you’re stuck).

Now, to do the very same thing with jQuery, all you have to do is this:

$('#result').load('http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');

Go ahead and try it in the Console. Change the ime parameter, and you’ll see that the text on the page will change to Hello [name], where [name] will be the parameter you entered.

⚠️ I won’t go into the basics of using jQuery, as it’s been here for a very long time, and there’s a vast amount of tutorials written about it. Start with the official docs if you want to learn more.

The important thing to note here is that .load must be chained to a so-called jQuery selection, as mentioned in the .load() documentation. We loaded the data from the server and placed the returned text into the element with an id result.

Shorthand methods

By looking at the docs, you can see that there are more of these so-called shorthand methods for making AJAX calls, all of which could be done with the most versatile ajax function.

The example from before could be done using the get shorthand method:

    var link = 'http://nikola-breznjak.com/_testings/ajax/test1.php';
    var data = {ime:"Nikola"};
    var callback = function(result) {
        $('#result').html(result);
    }
    $.get(link, data, callback);

If you don’t want to pass any parameters, it gets even simpler:

    var link = 'http://nikola-breznjak.com/_testings/ajax/test1.php';
    var callback = function(result) {
        $('#result').html(result);
    }
    $.get(link, callback);

Rewriting the mini project

I prepared the same demo page as in the previous post, but with jQuery already included so you can test this by just pasting the code below in the Console. I encourage you first to try it yourself and then compare your solution with mine below.

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
$.getJSON(link, function(result){
    var oglasiHTML = '';
    $.each(result, function(index, oglas){
        var klasaCijene = '';
        if (oglas.cijena < 100){
            klasaCijene = 'is-success';
        }
        else if (oglas.cijena >= 100 && oglas.cijena < 300){
            klasaCijene = 'is-info';
        }
        else if (oglas.cijena >= 300){
            klasaCijene = 'is-danger';
        }

        oglasiHTML += `
            <div class="columns">
                <div class="column is-one-quarter">
                    <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                </div>
                <div class="column">${oglas.tekst}</div>
            </div>
        `;
    });

    $('#oglasi').html(oglasiHTML);
});

There are a few things that I’d like to point out here:

  • I used the getJSON function to call my API located on the URL that’s saved in the link variable. This is because I know that this API returns a JSON response (you can check by opening that link in the browser).
  • I used the jQuery each function to iterate over the result.
  • I used the template literals to construct the final oglasiHTML in a much cleaner way than we did that in the previous post with using concatenation.
  • The core logic remained the same as in the first post, with the exception of not having to use the for loop and indexes to access each element of the array.

I want more examples

Say you have this demo page, and you need to make the newsletter signup form use AJAX instead of going to a new page when you click the Subscribe button. Right now the API (located at http://nikola-breznjak.com/_testings/ajax/email.php) doesn’t actually process what you send to it, but try to send data with the request as well for practice.

How would you do it? Where would you start?

Well, here are a few search terms you could Google:

  • `form submit jquery’
  • post data

Again, here’s my solution, but I encourage you to try it yourself first.

$('form').submit(function(ev){
    ev.preventDefault();
    var url = $(this).attr('action');
    var formData = $(this).serialize();
    $.post(url, formData, function(response){
        $('#newsletter').html('Thank you for subscribing, please check your email.');
    });
});

There are a few things that I’d like to point out here:

  • I was able to use the form selector without any id because it’s the only form on the page. If there were more forms on the page, I’d have to distinguish them by using an id (which is always a good practice, even if it’s just one form)
  • I used jQuery’s submit function to set an event handler that will be executed when the form will be submitted (Subscribe button clicked, or ENTER pressed while in one of the fields)
  • I used the ev.preventDefault() to prevent the form from “doing its thing” and loading the ’email.php’ page, as its default behavior
  • I used $(this).attr('action') to extract the API URL from the form definition it the HTML (feel free to check it out in the element inspector)
  • I used $(this).serialize() to encode a set of form elements as a string which I then passed to the jQuery post shorthand function. This function sends a request to the server using the POST method, which (as we learned in the previous post) is the preferred way of sending some sensitive data that needs to be handled on the server
  • I used the html function on a div with the id newsletter to set its new content

Can I have one more, please?

Sure, but promise you’ll do it yourself first!

I do ?

OK then, let’s do this ?

Here’s a new demo page that you’ll use for this example.

⚠️ I’m using Bulma to make the site look pretty. As their website says:
‘Bulma is a free, open source CSS framework based on Flexbox and used by more than 150,000 developers.’
I’ll just say it’s really great and easy to learn, so make sure you check it out.

In this challenge, you have to create a gif search application using the Giphy Search API. As the docs state, you’ll need to get the API key by creating an app. Once you do that, you’ll be able to search their API like, for example, this: http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC. You can use this API key, but be sure to create your own if this one gets banned for too many requests ?‍

Once you fetch the gifs (or still images if you so choose), show them in the div with a class result (yes, class, not id ?).

Here’s the part where you roll up your sleeves, create it, feel proud of yourself ?, and then come here to check how I did it.

$('form').submit(function(ev){
    ev.preventDefault();
    var searchTerm = $('input').val();

    var apiLink = "http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&q=" + searchTerm;

    var output = '';
    $.getJSON(apiLink, function(images){
        $.each(images.data, function(i, im){
            output += `<img src="${im.images.downsized.url}"/>`;
        });

        $('.result').html(output);
    });
});

The only new, and potentially tricky, part here is the traversal of the JSON object that you get back from the API, but with just a bit training, you’ll get good at it.

If you open up this URL in your browser, you will see this

The returned JSON object consists of three properties:

  • data
  • pagination
  • meta

The data is an array of objects, and in one of its properties it has an array of images. In my example, I choose to display the downsized gif by accessing its url property.

Here’s a short gif of this in action:

Conclusion

That’s all for this blog post. I hope it was useful and that you’ve seen how much easier it is to make AJAX requests with jQuery vs. plain JavaScript. I also hope you liked the demo exercises ?
In the next blog post, we’ll see how to do this with the modern fetch API.

JavaScript

Making AJAX calls in pure JavaScript

Making AJAX calls in pure JavaScript

TL;DR

In this, beginner oriented, post I’ll show you how to make AJAX calls in pure JavaScript, step by step with few examples.

So, what is AJAX?

AJAX stands for:

  • Asynchronous – means that if you start some request (call some API), you can move on to another task before that request is finished. This is the direct opposite of when you execute something synchronously – in that case, you have to wait for it to finish before moving on to another task.
  • JavaScript – the best language ever ?
  • And – added ‘And’ as three letter acronyms just don’t cut it anymore
  • XML – Extensible Markup Language that no one on the web uses anymore :), JSON FTW 🙂

OK, but what does it do?

AJAX lets you load some new data to your web page, without the need to reload the whole webpage. This behavior makes your site feel faster and more responsive. Not to mention that nowadays this is the defacto standard. Namely, if you come across a site on which you fill out a form and submit it, and then it has to reload, the site basically screams at you: “OOOOOLD!”.

Where can I see it in action?

I’d argue that you can see it in action on any decent webpage nowadays. For example, load the Google website in your browser, and open the dev tools. On Chrome, you can do that with right-clicking a mouse and selecting Inspect, and then clicking in the Network tab.

If you also select the XHR filter and start writing something in the search bar, you’ll start seeing the AJAX requests. Very important to note here is that the site didn’t reload.

If you click on one of these items in the Name column and then click the Response tab, you’ll see the actual response that the server sent back.

⚠️ This is an important concept to remember: web works in a Request/Response kind of a way. A client (your browser) sends Request to some server, and the server returns a Response, which then client processes.

Another example of AJAX in action is when you are presented with a newsletter signup form on some site. You fill out the name and an email address, click send, and the site doesn’t refresh. Instead, you get the message right there like “you’ve been subscribed, check your email”.

This is great, but how do I use it?

No one likes the theory, but it actually may help here. To use AJAX in JavaScript, you need to do four things:

  • create a XMLHttpRequest object
  • write the callback function
  • open the request
  • send the request

I know I know, you must be like:

OK, OK, so let’s take those steps from above and turn them into code:

  • create a XMLHttpRequest object
    • var xhr = new XMLHttpRequest();
    • of course, you can name the variable differently as well, but I hope you know this much about JS, or programming in general, so won’t go into that here ?)
  • write the callback function
    • xhr.onreadystatechange = function() {};
  • open the request
    • xhr.open('GET', 'http://www.google.com');
    • the first parameter is the type of the request. Another common one is ‘POST’, and we’ll talk about it more in the next post.
    • the second parameter is the URL (a link) to which you want to send the request. In our case, that’s Google’s website.
  • send the request
    • xhr.send()
    • finally, send the request

If we put it all in one place, we get this:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {};
xhr.open('GET', 'http://www.google.com');
xhr.send()

Fine, but, erm, where do I test this?!

You’ll be a bit disappointed to learn that the code above doesn’t do much.

Besides, where could you test this? Well, for one thing, you can’t test it on your local machine in a way of creating an index.html and opening it in your browser.

You have to test this on some website that’s online. Examples speak more than words, so let’s go and open up http://www.google.com in your browser.

Now let’s do a few things:

  • open the dev tools
  • select the Elements tab
  • right click the html element and select Edit as HTML
  • delete everything and click outside of the box that appears and you’ll end up with a blank page
  • add a div to the body tag like this: <div id="result">Testing</div>

Next, in the Console tab of the dev tools, write this:

var clearResult = function() {
    document.getElementById('result').innerHTML = '';
}

and then call it like this: clearResult().

The purists will kill me for using var instead of let ?

To save you a lot of trouble by figuring out why using clear as the function name won’t work, check out this post.

Now, copy paste the following code to the Console tab and press Enter to execute it:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4){
        document.getElementById('result').innerHTML = xhr.responseText;
    }
};
xhr.open('GET', 'https://www.google.com');
xhr.send();

Woilà, what do you get? You just loaded Google’s main page back in ?

AJAX can only go so far, most of the time

If you try playing out with the URL in the open command, you’ll soon stumble upon CORS. It basically means that, if your domain is google.com, then you can’t load the data from:

  • some other domain like example.com
  • a subdomain like abc.google.com
  • a different port on the same domain like google.com:8080
  • a different protocol like http

There are ways to get around this (server proxy on the same domain, JSONP, CORS setting on the domain server, using browser plugins), and I encourage you to dig deeper and learn more about it on your own (or wait until I write about it in some other post).

I want more examples

Great, happy to provide you with them.

Load up my test site. Copy the AJAX function from above and replace https://www.google.com with http://nikola-breznjak.com/_testings/ajax/test1.php and observe what happens.

Try changing the link to http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola and see what happens then. This is called sending the parameter (ime) in the URL. Which brings me to the following difference…

GET vs. POST

There are two common methods for sending HTTP requests:

  • GET – used for most requests. The browser uses a GET method whenever it requests a new web page, CSS file, image, and so on. Use GET when you want to “get” something from the server.
  • POST – frequently used with web forms to send data to the server. Use POST when sending data that will be stored, deleted or updated on the server.

You can send parameters with GET in the URL, and that’s a benefit as well as the downside, as there’s a limit to the length of the parameters in a GET request (2048 chars), as well as there’s a security issue. With POST you can send way more data, and in a secure way.

XML vs. JSON

XML is short for eXtensible Markup Language, and you can learn more about it here. It used to be for transmitting structured data that’s easily parsable by computers. You’ll notice it’s similar to HTML; for example:

<phones>
    <phone>+38598123456</phone>
    <phone>+38598654321</phone>
</phones>

Though, TBH, it’s not used on the web, so I won’t bore you with it. What is used, extensively, on the web these days is JSON. It looks very much like JavaScript object literal, with one addition – the key also needs to be enclosed with double quotes. For example:

[
    {"phone":"+38598123456"},
    {"phone":"+38598654321"}
]

This is an array of objects which consist (currently) of one property called phone.

Mini Project

So, mini project time now. Let’s suppose that you work at a job where your boss says that you need to update this page to have the sidebar load the advertisement from the API that can be found here.

He also adds that you need to make it consistent to the current design (Bulma rocks btw!) and make the price be of different colors based on the following rules:

If the price (cijena in the API response) is below 100 make it some greenish color. If it’s between 100 and 300, make it some blueish color. If it’s more than 300, make it red.

How are you going to do it?

I encourage you to try it out for yourself and only then come back and see my approach below.

You should have this in the end:

You can totally test this now by pasting the code below in the Console on this page.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (xhr.readyState === 4){
        var oglasi = JSON.parse(xhr.responseText);
        var oglasiHTML = '';
        for (var i=0; i<oglasi.length; i++){
        var klasaCijene = '';
        if (oglasi[i].cijena <100){
            klasaCijene = 'is-success';
        }
        else if (oglasi[i].cijena > 100 && oglasi[i].cijena < 300){
            klasaCijene = 'is-info';
        }
        else if (oglasi[i].cijena > 300){
            klasaCijene = 'is-danger';
        }

            oglasiHTML += '<p><span class="tag ' + klasaCijene + '">' + oglasi[i].cijena + '</span>' + ' ' + oglasi[i].tekst + '</p>';
        }

        document.getElementById('oglasi').innerHTML = oglasiHTML;
    }
};

xhr.open('GET', 'http://nikola-breznjak.com/_testings/ajax/test2.php');
xhr.send();

Conclusion

That’s all folks, hope it was useful and see you next time when I’ll show you how much easier it is to do all of this with a jQuery. Sure sure, in some later posts we’ll come to the fetch API as well. But first, baby steps ?

Books

Peak: Secrets from the New Science of Expertise – K. Anders Ericsson

Here are my favorite quotes from the book Peak: Secrets from the New Science of Expertise by K. Anders Ericsson.

You have to keep upping the ante: run farther, run faster, run uphill. If you don’t keep pushing and pushing and pushing some more, the body will settle into homeostasis, albeit at a different level than before, and you will stop improving.

The best way to get past any barrier is to come at it from a different direction, which is one reason it is useful to work with a teacher or coach. Even the most motivated and intelligent student will advance more quickly under the tutelage of someone who knows the best order in which to learn things, who understands and can demonstrate the proper way to perform various skills, who can provide useful feedback, and who can devise practice activities designed to overcome particular weaknesses.

You seldom improve much without giving the task your full attention.

Deliberate practice involves well-defined, specific goals and often involves improving some aspect of the target performance; it is not aimed at some vague overall improvement. Once an overall goal has been set, a teacher or coach will develop a plan for making a series of small changes that will add up to the desired larger change. Improving some aspect of the target performance allows a performer to see that his or her performances have been improved by the training. Deliberate practice is deliberate, that is, it requires a person’s full attention and conscious actions. It isn’t enough to simply follow a teacher’s or coach’s directions. The student must concentrate on the specific goal for his or her practice activity so that adjustments can be made to control practice.

You don’t build mental representations by thinking about something; you build them by trying to do something, failing, revising, and trying again, over and over. When you’re done, not only have you developed an effective mental representation for the skill you were developing, but you have also absorbed a great deal of information connected with that skill.

JavaScript

Don’t name your global JavaScript function ‘clear’

TL;DR

Same as the title, don’t name your global JavaScript function clear.

TL;DR

I learned the hard way not to use clear as the name for my global JavaScript function.

Given the example below:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test 1</title>

    <script>
        function clear() {
            document.getElementById('result').innerHTML = '';
        }
    </script>
</head>

<body>
    <button id="clear" onclick="clear()">Clear</button>
    <div id="result">Testing</div>
</body>

</html>

and clicking the Clear button, the Testing text will just not be removed.

I found this very cool StackOverflow explanation of why is that. The gist of it is that this way the document.clear function is being called, and simply renaming it to something like clearResult works fine.

Books

How we implemented the book club idea in our engineering team

TL;DR

In this post I’m going to show you:

  • how we implemented the book club idea in our engineering team
  • what book we read
  • how we liked it,
  • and share a few learnings, comments and (as I usually do in my book posts) quotes

Those interested in some data metrics, scroll to the end of the post, after the quotes 🙂

What book did we read?

We read the book called The Phoenix Project: A Novel about IT, DevOps, and Helping Your Business Win by Gene Kim, Kevin Behr, and George Spafford. This is a book that, arguably, everyone in IT should read.

The book is really awesome, and here’s the Amazon rating:

If you don’t trust Amazon for some reason, here’s the Goodreads rating:

The rating score of 4.25 out of 5 from almost 19k votes is a lot on Goodreads.

How did we do it?

We started reading the book on Jan 21st and finished it on Mar 11th. So, for 6 weeks we read approximately 50 pages per week and then discussed it in our mobile dev team meetings.

This is only 10 pages per workday, in case you were wondering. Here’s a short post on the math behind reading 30 books per year in case you’re interested.

What did we learn?

We learned that there are 4 types of work:

  • business projects
  • internal projects
  • changes
  • unplanned work

We learned some new phrases like FUBAR and MOADF, and we learned that everyone needs idle time, because if no one has idle/slack time, WIP (work in process) gets stuck in the system just waiting.

Also, we learned that getting the whole company working together to the same common goals only works if people know what the goals are. So, it’s good to have OKRs/KPIs/yourVersionOfGoalTracking publicly available and set by each department and their team members.

What discussions did the book start

The book also spurred some exciting discussions about:

  • how could we get to the single-piece flow
  • how to deal with unplanned work
  • what to do when asked to deploy something on Friday
  • what are our bottlenecks
  • how does our WIP look like
  • what ticket management systems we used in the past, etc.

What we didn’t quite like

There were some things that we didn’t like:

  • the ending was too happy-go-lucky; we expected something more along the lines of a Game of Thrones ending
  • Bill’s wife
  • Brent was too realistic, gave few of us scary flashbacks
  • Bill didn’t treat developers with respect. I quote:
    • “Developers – I had forgotten how quirky they can be. To me, they seem more like indie musicians than engineers.”

Characters

Speaking of characters, it seems like we all liked the Eric character, which could be described as a mix of Doc and Jack Sparrow. That also knows a lot about process and IT and also surfs not only the internet.

Since every good novel has to have a villain, this one did as well. We liked the fact that Sarah got what was coming for her in the end. And we even toyed with an idea of who would play this character in the “The Phoenix Project” movie. Here are a few options that were mentioned:

Some quotes

As usual in my book posts, here are some quotes that we liked:

  • “Until code is in production, no value is actually being generated, because it’s merely WIP stuck in the system.”
  • “He has a well-deserved reputation as one of the most fun people in the company to travel with. The size of his expense reports proves it.”
  • “Practice creates habits, and habits create mastery of any process or skill.”
  • “A good day feels like my staff panicking about the size of the commission checks we’re going to be writing them”
  • “I’ve realized that having people give you honest feedback is a rare gift.”
  • “You need to get everything in version control. Everything. Not just the code, but everything required to build the environment. Then you need to automate the entire environment creation process. You need a deployment pipeline where you can create test and production environments, and then deploy code into them, entirely on-demand. That’s how you reduce your setup times and eliminate errors, so you can finally match whatever rate of change Development sets the tempo at.”
  • “Developers – I had forgotten how quirky they can be. To me, they seem more like indie musicians than engineers.”
  • “Any COO who doesn’t intimately understand the IT systems that actually run the business is just an empty suit, relying on someone else to do their job.”
  • “Effectively managed IT is a significant predictor of company performance.”
  • “IDC, the analyst firm, says that there are 11M devs and 7M operations people on the planet.”
  • “To tell the truth is an act of love. To withhold the truth is an act of hate. Or worse, apathy.”
  • “In these competitive times, the name of the game is quick time to market and to fail fast.”
  • “Turning around, he says, “In any system of work, the theoretical ideal is single-piece flow, which maximizes throughput and minimizes variance. You get there by continually reducing batch sizes. “You’re doing the exact opposite by lengthening the Phoenix release intervals and increasing the number of features in each release. You’ve even lost the ability to control variance from one release to the next.”

Show me the data!

So, it does seem that we liked it and had fun, but how do you measure that?

This is how much we liked the book on a scale from 1-10:

Funny piece of trivia was that iOS devs used floats, and Android devs used integers. ?

This is how much we liked the book club implementation on a scale from 1-10:

And, finally, this is how likely we want to do this again in Q2 on a scale from 1-10:

I promise I didn’t set this graph up on purpose to look like this, but it does look kinda cool. ?

Conclusion

We liked this experiment and will continue doing it. I hope you found it valuable and that you also may wanna try out this within your teams. If you have any questions, please ask in the comments section.

And, a question for those that already conducted book clubs in your engineering organizations, what books did you read?

How we implemented the #book #club idea in our #engineering team https://t.co/lLQ5LuVUw6

— Nikola Brežnjak (@HitmanHR) March 25, 2019

Books

The Productivity Project – Chris Bailey

Here are my favorite quotes from the book The Productivity Project by Chris Bailey.

Make a list of all the things you’re responsible at your work. Then, ask yourself which is the most important item on that list and go do it.

At the end of every day decide which three tasks you want to accomplish by the end of the next day.

Manage your energy, not time.

Write and send a letter to yourself in the future.

Limit your time for a certain task to half of what you thought it’s going to take and see how it goes.

Don’t sort emails in folders – search for them.

Alcohol has a significant impact on your energy levels and productivity.

The brain can’t tell much difference between visualization and actual experience. Therefore, at the end of the day recall the positive and meaningful parts of your day – that way you double the significant experiences of your day.

77% of what we think is negative, counterproductive, and works against us. Therefore, force yourself to feed your brain with positive thoughts.

I’ve learned most from the meditation experiment where I lived in isolation for 10 days and meditated for 35+ hours.

Busyness is no different from laziness when it doesn’t lead you to accomplish anything.

You’re 7 times as likely to be highly engaged at work if If your best friend works at the same place.

The best attitude to have with productivity is never to be satisfied but to find ways to cultivate happiness continually.

Please stop multitasking 🙂

Books

The Coaching Mindset – Chad W. Hall

Here are my favorite quotes from the book The Coaching Mindset: 8 Ways to Think Like a Coach by Chad W. Hall.

Rather than tell people what to do, I helped people tell themselves what to do.

Don’t try to solve the problem for them, help them to get to the solution themselves.

When you think the highest value you bring to your coaching client is your intellect, your brilliance, your awesome problem-solving abilities, your creativity, or your whatever, you get in the way. That’s because coaching is about bringing out the intellect, brilliance, awesome problem-solving ability and creativity of your client. Coaching is a chance for the client to shine, not for you to shine.

The coach’s brain works not to solve, but to facilitate the client’s solving. The coach’s brain is not trying to think two, three, or four steps ahead, but to be with the client in the present moment as she thinks.

I am suggesting that you treat the coaching conversation like an adventure movie in which the client is the star, the hero, the main character, and the one moving the action forward.

The bigger the client’s challenge, the more important it is to let the client be the hero.

After all that thinking you might finally ask, “What can you do to make this a priority?” The problem here is that your question is the result of too much processing. A far better question would be the first question you asked yourself: “What do you mean by stuck?”

Great coaches train themselves to notice their own thinking and to stop or back up the thinking process so they say simple, primitive stuff that invites the client to process.

Primitive questions are powerful invitations for the client to explore something. Like: What do you make of that? How should we get started? Where are we in this conversation? What about that is really important to you? What’s a good way to unpack this? What’s your decision-making process need to be?

Whatever your client says, just go with it. Go with positivity, curiosity and a spirit of “Yes.”

The enemy of curiosity is judgment. On the other hand, curiosity opens up the learning process.

Pretending to know or assuming you know is a bad thing.

This sounds like a really important issue for you. What’s the best way for us to get started with it?

Don’t re-live the things your clients share as if it happened to you.

Your ability to remain somewhat objective is one of the greatest gifts you can give your client because it becomes the bridge to greater insight. Your objectivity merely enables you to invite the client to get on the balcony where he can see himself and his situation more clearly.

Page 12 of 51« First...10«11121314»203040...Last »

Recent posts

  • When espanso Breaks on Long Replacement Strings (and How to Fix It)
  • 2024 Top Author on dev.to
  • Hara hachi bun me
  • Discipline is also a talent
  • Play for the fun of it

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (78)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (41)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak