Sitemap
Ollie

Ollie

Working with Javascript

7 min readJun 14, 2017

I learnt the basics of Javascript whilst I was working as an intern for a company in Amsterdam. Before I started, I had very little knowledge of Javascript and knew the basics of jQuery.

I wanted to write my application is Javascript as when I was working as an intern, I was unable to use jQuery as it relies on a large library. Whilst jQuery has the advantage of making it quicker and easier to code, if you only need to use a small amount of jQuery on a website, you are loading a lot of code that is not going to be used. It does also sort out compatibility issues between browsers, however with the most recent version of Javascript, these are not so much of a problem.

I started off by creating a function called app. This function is used to contain all of the code required for the application to work.

The function is invoked by using the code on line 8. What this means, is that the function cannot run until the window has loaded. This includes content such as text and images. It is important that all elements of the page have loaded before the Javascript runs, as it may cause errors or may not work properly.

An Gist showing a function and how it is invoked

I then created a section that would contain all of the variables used to store elements in the DOM (Document Object Module). I wanted to include most variables within the app function, as this meant that the variable names could be used within all functions contained within the app function.

Variables that are declared within a function are local variables, meaning that they can only be used within that function. Variables that are declared outside of a function can be used throughout the whole Javascript file. Variables can be anything, such as text, integers and elements.

A Gist showing an example of a local and global variable
A Gist showing different ways variables can be used

In order to ensure that the user is connected to a secure connection using https, I used an else/if statement. This code works by checking whether the page has a secure connection. If it does not, then it will automatically change to a secure connection through https. This is neccessary as geolocation only works through a secure connection and cant work if the connection is not secure. An else/if statement works by checking whether a specified condition. If the condition is met, the code will run, if the condition is not met, another piece of code will run instead.

A Gist showing the code used to ensure the page is connected using https

The next step is to see whether or not the browser supports geolocation. If the the browser does not support geolocation, a message is logged to the console to state that the condition is met. If the browser does support geolocation, then a message is sent to the console to state that browser does support geolcoation. The code will then move on and run the next line of code.

A gist showing how to determine whether or not a browser supports geolocation

The code will continue running until line 22 as the two functions “locationSuccess” and “Error” have not been called yet. Line 22 is a callback function, and this code will determine what function to run. If the browser does not support geolocation, the browser will run the error function. If the browser supports geolocation, it will run the locationSuccess function. It will then run the code within the opening and closing parentheses.

A Gist showing a callback function determining what code function to execute

Within the location success function, it will start by creating a console log to display the message on line 4. Variables are declared on line 7 and 8, the variables will store the users location. A callback function is then used to run the success function. This function requires two paramters, the latitude and longitude.

I needed to use the users coordinates as parameters, as it would allow me to use the user’s coordinates outside of the locationSuccess function.

The next step was to find the closest stations to the user. I created a function called findClosestStations. Within this function, a URL would be created using the “closestStationsURL” as a template. The two variables “userLatitude” and “userLongitude” would be replaced with the user’s coordinates to generate a URL which will be used to send an Ajax request to the server.

A Gist showing how a dynamic url is created

Once the URL to make the request has been created, a request can then be made to the server. To do so, you will need do an Ajax request. The advantage of using an Ajax request, is that it is done asyncronousy. This means that the page does not need to be reloaded to get the data.

A Gist showing an example of an Ajax Request
  • Line 1 — A new request is created
  • Line 2 — The request is opened, the request type is a “GET” request, meaning that you are just going to get the data from the API
  • Lines 4–12 — If the request is successful, the function will run and any code within this function will run.
  • Line 5–12 — An if/else statement is used to determine the status of the request. If it is between 200 and 399, it is successful. If it is outside of these numbers, this means the connection is successful, however there may be an error with the request.
  • Lines 14–16 — If the request has failed, usually due to an error with the connection, then the error function will run.
  • Line 18 — this will send the request to the server.

In order to generate the buttons, I needed to define a variable called closestStationsRes for the response data (if the request is successful). I then created another variable called closestStationData to access the array in the response data called “result”. This array contained all of the stations in order of distance.

Get Ollie’s stories in your inbox

Join Medium for free to get updates from this writer.

I then used a for loop to go through the closestStationsData variable array. As I only needed the five closest stations, I set the loop to stop after it has gone through the array five times.

I created variables, named according to the information I needed from the API, to get the data I needed to use to create the buttons.

I used a console log to store all of the data I received from the API, and created a new variable as a template for the button.

On line 30, this code then inserts the buttons in to the closestStationsDiv.

A Gist showing how I looped through an array to get the data, and then used the data to generate the buttons and insert it in to a DIV.

If there was an error, instead of leaving the user unsure about what has happened, I wrote some code that would insert a message informing the user that there was an error and the closest stations could not be found. On line 25, this code is required to run the function.

The next step was to create a function that allows users to search for trains. I started off by creating an event listener that listens for a click event on the submit button for the form users will use to enter a station and perform a search.

  • Line 2 — this is the click event, this will listen for the click event on the submit button, and run the function “searchForTrains”.
  • Line 5 — this is the function that will run when clicked. The “e” parameter is the element that is clicked.
  • Line 8 — this is the variable that is used to store the element that has been clicked, which would be the submit button.
  • Line 11 — this prevents the default action when a button is pressed, which is a page refresh.
  • Line 14 — this takes the value that the user has entered within the search form.
  • Line 19 — this is the template for the URL that will be used to make an API request. It will use the originValue variable to create the URL.
A Gist showing part of the searchForTrains function used to send an API request to the server and return the relevant data.

The next stage is to create an API request to get the data that is required, such as train times, origins, destinations and other relevant information. I have not included this code as I have already explained how an Ajax request is made, and how the data is accessed from the response data.

The API used to provide me with information about trains sometimes returns data that is not useful for humans to understand. For example, if a platform number is not available, the server will return null.

In order to make this more useful to humans, I used an else if statement to determine whether the response was “null” and change it to unavailable instead.

A Gist showing examples of where I have used else/if statements to make the data more understandable for humans

Once all the data has been requested from the API and all the variables to store all the relevant data required, I then created a DIV template that would take all of the data, place them in the relevant DIVs and then insert it in to the wrapper for the search results. After it has been inserted, the clases “hidden” are then removed to display the wrapper and container, which will contain the train service information to the user. This code is contained within a “For” loop, the loop is repeated for the number of entries in an array, which will depend on how many train services there are. I used the “.length” property to find the length of the array. If for example there were 12 services, the loop would run 12 times, fetching the information required from each individual array, and generate the templates to show all of the information.

A Gist showing part of the function used to generate the buttons and insert them in to the search results DIV

In order to retrieve the calling points, another ajax request was made to another API. The URL to retrieve the service information is generated using the service ID. This information is retrieved using the API used to get the service information. I used datasets to store the service ID in the “Show More” button. A click event is then added to the button. When the button is pressed, I am able to use the service ID by setting up a variable that takes the information from the dataset then creates a dynamic URL using the service ID. On line 13, the targetServiceId variable is the variable that is used to access the dataset that provides the service ID.

I have tried to explain the code in as consise and succinct way, however In total the script.js file has over 500 lines of code. The code is also available on Github and can be found at https://github.com/norrisollie/final-trackk

I have commented the code clearly, with each comment explaing what each line of code does. I always make an effort to comment code, as it can be easier for people to understand and see what each line does. I have also spaced it so it is clear and understandable.

--

--