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
Books

Too many books, not enough time

TL;DR

How about instead of just adding more new books to our read pile (and even more to the never-ending to-read pile), we revisit our list of the books that we’ve read and in 2020 we not just re-read them, but study them?

!TL;DR

Quotes are great

“The greatest satisfaction comes from mastering something that is truly difficult.”
~ Abraham Maslow

A positive fact

All of us are readers in this group, and we had to go through a lot of content to find the one that’s valuable. We can think of that as a process of getting the signal from the noise.

A sad fact

Even though we read a lot of books (and we may be looking into techniques to increase that number), we are not oblivious to the fact that there are just too many books and not enough time. Moreover so, we realize that after a certain amount of books that we’ve read in a certain category, the new ones are just not yielding the same ROI (I being the ever so slightly limited time). Most of them feel like they’re rehashing the ideas and are just geared toward the ‘current’ generation.

A little bit of math

Consider for a moment that we read 60 books per year (A lot, right? Well, here’s the math behind reading 30 in a year). What if, in 2020, instead of just adding new books to the read pile, we set a goal only to read 30 (half of that, so adjust your math accordingly, please). But with a twist.

The twist and the ?

What if we revisit all the books that we’ve read in our career so far and commit to not only re-reading them in 2020, but actually studying them? So that we won’t just know ‘oh, yeah, I read that somewhere in the XYZ book,’ but instead we’ll have the actual book in RAM if you will (with UPS, of course). Sure, I’d reserve a slot for 10 new ones just in case 🙂

For added points, please proceed here

I’d love to hear what you think about the idea presented above 🙏. And also, I’d like to learn what were the signal vs. noise books in your career so far? To not make this into some long list, let’s cap it at five books.

So how about you, mister?

OK, OK, thought I’d get away with it 😎, here’s my entry:

  • Leadership and self-deception
  • Time management made simple
  • How to win friends and influence people
  • Think and grow rich
  • Little prince

Conclusion

One thing is definite: our time. Let’s use it as effectively as possible by reading the books that bring the biggest bang for the buck.

Books

Scrum: The Art of Doing Twice the Work in Half the Time – Jeff Sutherland

Here are my notes from the practical book Scrum: The Art of Doing Twice the Work in Half the Time.

Several of us were reading it as a part of a ‘smaller book club’ and we all echoed the same feeling about the book: we love it and will not only look to apply it in the work environment but also at home in our personal lives.

Ingredients for scrum

  • Product Owner
    • What and Why needs to be done
    • Knows the market, the customer and has a vision
  • Team (3-9 people)
    • Decide on the Who and How
  • Scrum Master
    • Coaches the Scrum framework and removes waste
  • Create and prioritize the Backlog
    • Constantly evolving
  • Refine and estimate the Backlog
    • Planning Poker with Fibonacci sequence
  • Sprint planning
    • Team, Scrum Master, and the Product Owner
    • Always of fixed length (from 1 to 4 weeks in general)
    • Velocity
      • Sum of points done in one Sprint
    • Sprint goal
      • Everyone has to agree on one sprint goal in the Sprint
  • Scrum board
    • Has lanes ToDo, Doing, Done (we use Clubhouse)
  • Burndown chart
    • Chart showing a number of points done per day
  • Daily Stand-up or Daily Scrum
    • 15 min max meeting where you answer three questions:
      • What did you do yesterday to help the team finish the Sprint?
      • What will you do today to help the team finish the Sprint?
      • Is there any obstacle blocking you or the team from achieving the Sprint goal?
  • Sprint review or Sprint demo
    • Show what was done in a Sprint
      • Show what’s totally finished by the DoD (Definition of Done)
  • Sprint retrospective
    • What went right?
    • What could have gone better?
    • What is the improvement in the process that we as a team can implement right away (in the next Sprint)?
    • The process should be blameless – we’re looking at the process, not people!

Takeaways per chapter

  • CH #1 – The way the world works is broken
    • Planning is useful. Blindly following plans is stupid.
      • It’s just too tempting to draw up endless charts. All the work needed to be done on the massive project laid out for everyone to see – but when detailed plans meet reality, they fall apart. Build into your working method the assumption of change, discovery, and new ideas.
    • Inspect and adapt
      • Every little while, stop doing what you’re doing, review what you’ve done, and see if it’s still what you should be doing and if you can do it better.
    • Change or die
      • Clinging to the old way of doing things, of command and control and rigid predictability, will only bring failure. In the meantime, the competition that is willing to change will leave you in the dust.
    • Fail fast so you can fix early
      • Corporate culture often puts more weight on forms, procedures, and meetings than on visible value creation that can be inspected at short intervals by users. Work that does not produce real value is madness. Working product in short cycles allows early user feedback and you can immediately eliminate what is obviously wasteful effort.
  • CH #2 – the origins of Scrum
    • Hesitation is death
      • Observe, Orient, Decide, Act. Know where you are, assess your options, make a decision, and act!
    • Look outward for answers
      • Complex adaptive systems follow a few simple rules, which they learn from their environment.
    • Great teams are
      • They are cross-functional, autonomous, and empowered with a transcendent purpose.
    • Don’t guess. Plan, Do, Check, Act.
      • Plan what you’re going to do. Do it. Check whether it did what you wanted. Act on that and change how you’re doing things. Repeat in regular cycles, and, by doing so, achieve continuous improvement.
    • Shu Ha Ri
      • First, learn the rules and the forms, and once you’ve mastered them, making innovations. Finally, in a heightened state of mastery, discard the forms and just be – with all the learning internalized and decisions made almost unconsciously.
  • CH #3 – Teams
    • Pull the right lever
      • Change team performance. That has much more impact – by several orders of magnitude – than individual performance.
    • Transcendence
      • Great teams have a purpose that is greater than the individual; e.g. burying General MacArthur, winning the NBA championship.
    • Autonomy
      • Give teams the freedom to make decisions on how to take action – to be respected as masters of their craft. The ability to improvise will make all the difference, whether the unit is reporting on a revolution in the Middle East or making the sale.
    • Cross-functional
      • The team must have every skill needed to complete a project, whether the mission is to deliver Salesforce.com software or capture terrorists in Iraq.
    • Small Wins
      • Small teams get work done faster than big teams. The rule of thumb is 7 members ± 2. Err on the small side.
    • Blame is stupid
      • Don’t look for bad people; look for bad systems – one that incentivizes bad behavior and rewards poor performance.
  • CH #4 – Time
    • Time is finite. Treat it that way.
      • Break down your work into what can be accomplished in a regular, set, short period – optimally 1 to 4 weeks. And if you’ve caught the Scrum fever, call at the Sprint.
    • Demo or die
      • At the end of each sprint, have something that it’s done – something that can be used (to fly, drive, whatever)
    • Throw away your business cards
      • Titles are specialized status markers. Be known for what you do, not how you’re referred to.
    • Everyone knows everything
      • Communication saturation accelerates work.
    • One meeting a day
      • When it comes to team check-ins, once a day is enough. Get together for 15 minutes at the daily standup, see what can be done to increase speed, and do it.
  • CH #5 – Waste is a crime
    • Multitasking makes you stupid
      • Doing more than one thing at a time makes you slower and worse at both tasks. Don’t do it. If you think this doesn’t apply to you, you’re wrong – it does.
    • Half-done is not done
      • A half-built car simply ties up resources that could be used to create value or save money. Anything that’s “in process” costs money and energy without delivering anything.
    • Do it right the first time
      • When you make a mistake, fix it right away. Stop everything else and address it. Fixing it later can take you more than 20 times longer than if you fix it now.
    • Working too hard only makes more work
      • Working long hours doesn’t get more done; it gets less done. Working too much results in fatigue, which leads to errors, which leads to having to fix the thing you just finished. Rather than work late or on weekends, work weekdays only at a sustainable pace. And take a vacation.
    • Don’t be unreasonable
      • Goals that are challenging our motivators; goals that are impossible are just depressing.
    • No heroics
      • If you need a hero to get things done, you have a problem. Heroic effort should be viewed as a failure of planning.
    • Enough with the stupid policies
      • Any policy that seems ridiculous likely is. Stupid forms, stupid meetings, stupid approvals, stupid standards are just that – stupid. If your office seems like a Dilbert cartoon, fix it.
    • No assholes
      • Don’t be one, and don’t allow the behavior. Anyone who causes emotional chaos, inspires fear or dread, or demeans or diminishes people needs to be stopped cold.
    • Strive for flow
      • Choose the smoothest, most trouble-free way to get things done. Scrum is about enabling the most flow possible.
  • CH #6 – Plan reality, not fantasy
    • The map is not the terrain
      • Don’t fall in love with your plan. It’s almost certainly wrong.
    • Only plan what you need to do
      • Don’t try to project everything else years in advance. Just plan enough to keep your teams busy.
    • What kind of dog is it?
      • Don’t estimate in absolute terms like hours – it’s been proven that humans are terrible at that. Size things relatively, by what breed of dog the problem is, or T-shirt size, or, more commonly, the Fibonacci sequence.
    • Ask the Oracle
      • Use a blank technique, like the Delphi method, to avoid anchoring biases such as the halo effect or bandwagon effect or just plain stupid groupthink.
    • Planing poker
      • Use planning poker to quickly estimate the work that needs to be done.
    • Work is a story
      • Think first about who will be getting value from something, then about what it is, and then why do you need it. Humans think in narratives, so give them one. As an X, I want Y, so that Z.
    • Know your velocity
      • Every team should know exactly how much work they can get done in each Sprint. And they should know how much they can improve that velocity by working smarter and removing barriers that are slowing them down.
    • Velocity x Time = Delivery
      • Once you know how fast you’re going, you’ll know how soon you’ll get there.
    • Set audacious goals
      • With Scrum it is not that hard to double production or cut on delivery time in half. If you do it the right way, your revenue and stock price should double as well.
  • CH #7 – Happiness
    • It’s the journey, not the destination
      • True happiness is found in the process, not the result. often we only reward the results, but what we are really want to reward his people striving towards greatness.
    • Happy is the new black
      • It helps you make smarter decisions. Plus, when you’re happy, you’re more creative, less likely to leave your job, and more likely to accomplish far more than you’ve ever anticipated.
    • Quantify happiness
      • It’s not enough to just feel good; you need to measure that feeling and compare it to actual performance. Other metrics look backward. Happiness is the future-looking metric.
    • Get better every day – and measure it
      • At the end of each Sprint, the team should pick one small improvement, or kaizen, that will make them happier. And that should become the most important thing they’ll accomplish in the next Sprint.
    • Secrecy is poison
      • Nothing should be secret. Everyone should know everything, and that includes salaries and financials. Obfuscation only serves people who serve themselves.
    • Make work visible
      • Have a board that shows all the work that needs to be done, what is being worked on, and what is actually done. Everyone should see it, and everyone should update it every day.
    • Happiness is autonomy, mastery, and purpose
      • Everyone wants to control their own destiny, and get better at what they do, and serve a purpose greater than themselves.
    • Pop the happy bubble
      • Don’t get so happy that you start believing your own bullshit. Make sure happiness is measured against performance and if there is a disconnect, be prepared to act. Complacency is the enemy of success.
  • CH #8 – Priorities
    • Make a list. Check it twice.
      • Create a list of everything that could possibly be done on the project. Then prioritize it. Put the items with the highest value and lowest risk at the top of the backlog, then the next, and then the next.
    • The Product owner
      • She translates vision into Backlog. She needs to understand the business case, the market, and the customer.
      • Has knowledge of the domain and the power to make final decisions. Is available to answer questions and is accountable for delivering value.
    • A leader isn’t a boss
      • A product owner sets out what needs to be done and why. How the team accomplishes it and who accomplishes it is up to the team.
    • Observe, Orient, Decide, Act (OODA)
      • See the whole strategic picture, but act tactically and quickly
    • Fear, uncertainty, and doubt
      • It’s better to give than to receive. Get inside your competitors OODA loop and wrap them up in their own confusion.
    • Get your money for nothing and your change for free
      • Create new things as long as those new things deliver value all stop be willing to swap them out for things that require equal effort. What in the beginning you thought you needed is never what is actually needed.
  • CH #9 – Change the world
    • Scrum accelerates all human endeavors
      • The type of project or problem doesn’t matter – Scrum can be used in any endeavor to improve performance and results
    • Scrum for schools
      • In the Netherlands, a growing number of teachers are using Scrum to teach high school. They see an almost immediate improvement in test scores of more than 10%. And they’re engaging all sorts a few students, from vocational to gifted.
    • Scrum for poverty
      • In Uganda, the Grameen Foundation is using Scrum to deliver agricultural and market data to poor rural farmers. The result: double the yield and double the revenue for some of the poorest people on the planet.
    • Rip up your business cards
      • Get rid of old titles, all managers, all structures. Give people the freedom to do what they think best and the responsibility to be accountable for it. You’ll be surprised at the results.
Books

Book club in our engineering team – Pragmatic Programmer

TL;DR

In this short post I’ll tell you:

  • how we implemented our third book club idea in our engineering team
  • what book we read
  • how we liked it,
  • and share a few quotes that we liked

You can read all about our other book clubs here:

  • 1st – The Phoenix Project (has way more info on how we’re doing it)
  • 2nd – It doesn’t have to be crazy at work

⚠️ If you’re thinking that there’s no time to read the books, check this post on the math behind reading 30 books per year.  If you think book club thing is cool, and you’d want to be a part of the group that’s ‘allowed’ to read ‘on the job’, shoot me an email ?

THE BOOK

  • This time we read the Pragmatic Programmer

DATA POINTS

  • avg(time to read) = 6 hours
  • avg(liked the book) = 6.9 / 10
  • avg(liked the book club) = 8.8 / 10

KEY TAKEAWAYS

  • Quality is a team issue – the team as a whole should not tolerate broken windows
  • Treat the documentation the same way you treat your code
  • Prototypes are disposable and shouldn’t go into production
  • Crashing early makes life a lot easier when debugging code
  • Decoupling is good, but as a group, we don’t subscribe to the idea that your software needs to be so flexible that swapping out databases would just be as easy as changing a line of code
  • Shell is way more powerful than GUI
  • Don’t be a slave to old code, always be ready to refactor
  • Don’t refactor and change functionality at the same time
  • Take the time to spell out connectionPool instead of cp
  • Treat code as gardening
  • “Why” is more important than the “what” – don’t blindly duplicate existing workflow when translating into code from manual processes
  • Try not to be a slave to the methodology
  • Overengineering is as bad as under-engineering
  • Premature optimization is bad
  • Making a project glossary to save time later on looking for acronym translations is a good idea
  • The code should have comments, but too many comments can be just as bad as too few
  • Attaching codenames to new projects/features is cool
  • Tailoring your message to the audience is an important skill to have
  • Don’t tell your boss that it’s done until it’s tested
  • Finding bugs early in the process saves money in the long run
  • Learn a new language every year, and read a tech book every month and read non-tech books as well
  • The word deadline comes from a line in prisons which if crossed by prisoners they’d get shot
  • The book is mostly a refresher of techniques/ideas that we already know – new book coming out for 20th anniversary
Books

The Coaching Habit – Michael Bungay Stanier

Here are my notes from a very practical book The Coaching Habit by Michael Bungay Stanier:

The book covers 7 questions:

  • Kickstart: What’s on your mind
  • AWE: And what else?
  • Focus: What’s the real challenge here for you?
  • Foundation: What do you want?
  • Lazy: How can I help?
  • Strategic: If you’re saying yes to this, what are you saying no to?
  • Learning: What was most useful for you?

  • The essence of coaching lies in helping others and unlocking their potential

  • If you need to have a lead in phrase, consider using: ‘out of curiosity’
  • Three vicious circles that plague our workplaces: overdependence, getting overwhelmed, and becoming disconnected.
  • Ask people more questions and give less advice
  • 45% of our waking behavior is habitual
  • If you spend too much time imagining the outcome, you’re less motivated to actually do the work to get there.
  • Think less about what your habits can do for you, and more about how this new habit will help the person or people you care about.
  • Charles Duhigg says that there are just five types of triggers: location, time, and emotional state, other people, and immediately preceding action.
  • I will ask just one question and then be quiet while I wait for the answer.
  • Coaching for performance is about addressing and fixing a specific problem or challenge. Coaching for development is about turning the focus from the issue to the person dealing with the issue, the person who’s managing the fire.
  • 3P’s: people, projects, patterns
  • The brain accounts for only 2% of the body weight, but it uses about 20% of the energy
  • The first answer someone gives you is rarely the only answer, and it’s rarely the best answer.
  • The brain counts like this: one, two, three, four…lots.
  • Stop offering up advice with a question mark attached. That doesn’t count as asking the question. If you’ve got an idea, wait. Ask, “And, what else?”, and you’ll often find that the person comes up with the very same idea that’s burning a hole in your brain.
  • The simple act of adding ‘for you today’ to the end of as many questions as possible is an everyday technique for making conversations more development than performance oriented.
  • Stick to the question starting with “What” and avoid questions starting with “Why”.
    • Why did you do that? => What were you hoping for here?
    • Why did you think this was a good idea? => What made you choose this course of action?
    • Why are you bothering with this => What’s important for you here?
  • The single biggest problem with communication is the illusion that it has taken place. ~ G.B. Shaw
  • 9 universal needs based on Marshall Rosenberg: affection, creation, recreation, freedom, identity, understanding, participation, protection, subsistence
  • Five times a second, at an unconscious level, your brain is scanning the environment around you and asking itself: it’s safe here, or is it dangerous?
  • After asking a question, just patiently wait for an answer.
  • Based on Karpman, there are three archetypal roles: victim, persecutor, and rescuer
  • While talking nod your head, make encouragement noises and maintain
  • Being busy is no measure of success
  • The essence of strategy is choosing what not to do. ~ Michael Porter
  • Acknowledge the reply of a person by saying, “Yes, that’s good”, instead of just going into another question.
  • People don’t really learn when you tell them something. They don’t even really learn when they do something. They start learning, start creating new neural pathways, only when they have a chance to recall and reflect on what just happened.
  • This is why, in a nutshell, the advice is overrated. I can tell you something, and it’s got the limited chance of making its way into your brain’s hippocampus, the region that encodes memory. If I can ask you a question and you generate the answer yourself, the odds increase substantially.x
  • What have you learned since we last met?
  • So, what was most useful here for you? What did you find most valuable about this chat? What worked best here?
  • Finish on a high note, and you make everything that went before it look better.
  • “Before I jump into a longer reply, let me ask you: What’s the real challenge here for you?
Books

Book club in our engineering team – It doesn’t have to be crazy at work

TL;DR

You can read all about how we implemented our 1st book club idea in our engineering team, and in this post, I’m going to do the same but with a new book. In this short post I’ll tell you:

  • how we implemented the second 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

What book did we read?

We read the book called It Doesn’t Have to Be Crazy at Work by Jason Fried and David Heinemeier Hansson.

It seems that the Goodreads and Amazon reviewers liked the book.

However, I’m not really sure why, because this is how much we liked (or better said didn’t) the book. So, 4.5/10 with a max rating of 6 says a lot.

How did we do it?

We read it in only three weeks which means it was a really easy read. This comes down to about 75 pages per week, which amounts to 15 pages per work day.

On average, it took us 2hr and 22 minutes to finish the book, or about 9 minutes per work day.

Here’s a short post on the math behind reading 30 books per year in case you’re interested.

What did we like?

Even though we didn’t like the book in general, it still had some parts that we liked:

  • Office hours idea
  • Stance towards interviews – and paying for spec work
  • Company is not a family
  • Salary negotiation is crap
  • Calm goodbyes
  • Fridays off during summer

What we didn’t like

A lot of the chapters were common sense, and we agreed with them (few mentioned above), but some of the things we just couldn’t agree with:

  • No goal setting
  • Not going out of your comfort zone – promoting mediocrity
  • It seems like the whole book is an advertisement for them
  • They support multiple versions
  • This most probably won’t work for a bigger company

Some quotes

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

  • We don’t mind leaving some money on the table, and we don’t need to squeeze every drop out of the lemon. Those final drops usually taste sour, anyway.
  • There is nothing so useless as doing efficiently that which should not be done at all.
  • Your company is a product. If you want to make the product better, you have to keep tweaking, revising, and iterating.

  • Comparison is the death of joy.

Conclusion

Even though we didn’t like the book in general, it definitely wasn’t a total waste of time. We already started with the next book (Pragmatic Programmer), and this time we hope the book to be better.

A question for those that already conducted book clubs in your engineering organizations – what books did you read?

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 ?

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

Recent posts

  • Caffeinate your Mac to prevent it from sleeping
  • Vibe Coding a Pokémon Search App with Cursor
  • Vibe Coding a Pokémon Search App with Replit
  • SendGrid Phishing Scam Attempts
  • Retrospective Questions

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$ (80)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (42)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • VibeCoding (2)
  • 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