A full example of using AJAX to grab data on a server

Creating an AJAX driven website

I said earlier that I created 2 domains on my new hosting package and on it I’m housing a development website, a whole website that stores scripts, websites and apps created for my personal learning and development.

At the heart of this is a process that uses AJAX to grab data from a file on my server, output it and format it visually using CSS.  You can see what I’ve done so far by logging on to http://www.jonniegrieve.co.uk/jg-lab.co.uk/index.html

At the time of writing it isn’t all that good to look at. I intend to fix this as soon as I’ve made sure all the functional elements work.

Anyway, below is the main script that drives the dynamic part of the home page.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'app/project.json');
xhr.onreadystatechange = function () {
 if(xhr.readyState === 4 && xhr.status === 200) {
 var project = JSON.parse(xhr.responseText); //APCONVERTY TEXT to JS format.
 varstatusHTML = '

Current Projects

';
statusHTML += '
    ‘; //open list
 for (var i=0; i
 if (project[i].status === true) {
statusHTML += '
  • ';
} else { statusHTML += '
  • ';
} statusHTML += project[i].projectName; statusHTML += ''; } statusHTML += ''; document.getElementById('active-projects').innerHTML = statusHTML; } }; xhr.send();

var xhr = new XMLHttpRequest(); 
xhr.open(‘GET’, ‘../Ajax/app/employees.json’);

This bit is familiar if you’ve seen my previous blogs. In these first 2 lines, we set the XMLHttpRequest object to a variable and open a connection to a file. In this case we’re opening a connection to an AJAJX compatible format of collecting data. A JSON file. ‘Once done, we have to tell AJAX what we want to do with that data.

We’ve already touched on the way we do this. Through a callback function. The main body of the callback function is actually an event handler. It’s a function that does something with an event. In this case, the event is *onreadystatechange* event and just like in any other function we give it instructions.

e.g.
xhr.onreadystatechange = function () {

Now that we’ve opened an event handler we then need to check for errors in the process of getting the data from the file, by making sure the script cycles through all the stages of the AJAX ready state and network status.

A readyState of 4, means that AJAX has gone through all 4 stages of the request process.  A status of 200 means that the network tests and file checks have all passed and AJAX is ready to grab and use data.

if(xhr.readyState === 4 && xhr.status === 200) { //on this line, check readyState and network status

Parsing and adding HTML

var employees = JSON.parse(xhr.responseText);

In this next part of the process a JavaScript method is used to parse the information i.e. to convert the information into a format that AJAX can use.  We’re using the JSON file format which is a plain text file. AJAX can’t do anything with plain text alone so it has to be converted and this is what the parse method does.

varstatusHTML = ‘

    ‘;

If we do have success in creating this AJAX connection, the HTML in this part of the page is going to be replaced. So we need to use JavaScript to add HTML dynamically. We do this by adding some HTML in a string and assigning it to a variable.

This has to be done piece by piece.  In a moment we’ll be using programming concepts such as loops and condition statement to generate the markup we need.  In order to display the information correctly, we need to make sure it matches certain conditions.

This means putting a condition statement inside a loop.

for (var i=0; i
if (project[i].status === true) {
statusHTML += ‘

  • ‘;


} else {
statusHTML += ‘

  • ‘;


}

We could probably find a way to go through all the entries in the JSON file without using a loop, but that would be arduous and time-consuming.  It’s better to just learn the value of loops.   All it needs a very simple for loops and counts incrementally the number of entries in your JSON file.

You don’t even need to know the number yourself.  As long as your JSON file is correctly formatted, by using project.length (where project is the variable name of the parsed data and length is the JavaScript method) this loop will have you covered.

Then we move on to the condition statement.  Remember these statements take a course of action based on whether a condition has been met.  e.g.

project[i].status === true

The script treats the JSON file as an array of values so it’s accessed as such in the condition.. This condition is looking through the JSON files for boolean values, because the condition being checked for is a boolean.

So if I was to create data such as this

” {
“projectName”: “Howtobuildaproject”,
“status”: “complete”
},
{
“projectName”: “BalsamiqMockup”,
“status”: “incomplete”
}

The condition would always fail because it doesn’t any boolean values (or values matching true or false).

So the above is no good to us.  We could fix that by maybe changing the condition to project[i].status === “complete” but I think it’s best to stick to simple true or false values.

statusHTML += project[i].projectName;
statusHTML += ”; close the list item.
}
statusHTML += ”;

To display the other field in the data, the projectName field, we access the values just as we did before, as an array.  We can do this because by the time we come to this line of the code, we’re still in the for loop. As long as the loop is running there’s still data to access and display.

Finally, the list item tag is displayed, the loop scope is closed and then the list element is closed. We’ve now created all the HTML we need to display from the script.

document.getElementById(‘active-projects’).innerHTML = statusHTML;

Finally we need some way to display the data to the screen.  We use innerHTML to display the HTML values stored in the statusHTML variable and then we find an element to display the data.  document.getElementById finds and element that has the id active-projects.

information to on the browser screen by selecting the element by its ID.
}
};
xhr.send();

The last bit is just a bit of housekeeping.  We close the callback function, the event handler and last but not least, tell AJAX to send the request to the server.

Conclusion

This is a fantastic little script that makes good use of AJAX. With the basic skeleton of a callback function you can get started with doing all sorts of things using data without having to leave the current page. But there’s jQuery methods out there that can help simplify the process even further. Which sounds like a good subject for my next blog.

Advertisements

Understanding Callbacks with AJAX

My current focus at the moment is fixed on AJAX. AJAX is a lot of fun to learn and something that makes working with JavaScript even more awesome, You’ve probably made use of AJAX throughout your time browsing the web. Doesn’t it make interacting with the web even more smooth and user friendly? Sending data through the web without having to leave the page. That is what AJAX does.

More about that in a moment. But I want to digress and talk about 2 new addon web spaces that I’ve added for my jonniegrieve.co.uk domain.

  • jonniegrieve.co.uk@jg-lab.co.uk
  • jonniegrieve.co.uk@wordpress-jonniegrieve.co.uk

I upgraded my hosting package to include mySQL access and compatibility with CMS (Content Management System’s) like WordPress. Hence the 2 addon domains I created.

JG lab is a name I gave to a folder on my drive where I keep websites, scripts I files I use for research, development and personal growth. I decided to create a website area for this purpose, allowing me to keep it separate from my portfolio.

And this is where AJAX comes in. There’s a course on Treehouse called AJAX Basics which guides you through a project that uses JSON and AJAX to create an employee check-in register that updates dynamically based on the values stored in the JSON file.

Which could easily be adapted for a little idea of mine. A dynamic list of projects and files that can be marked as either complete or incomplete. Nothing more than a column or section of the page that can be updated by the user once I’ve finished work on a project. I’ll share more about this once I’ve finalised the home page.

For now though I want to talk a little about what I’ve managed to learn about AJAX.

As I said before, AJAX is a dynamic JavaScript technology that allows you to get or retrieve information from a server without leaving the original page.

It does this by creating, opening and sending something called an XMLHttpRequest object and cycling through a series of steps known as the ready state. The 4 steps are as follows:

Making an AJAX Request

  • Create an XMLHttpRequest Object
  • Create a callback function! – The programming run when the server responds to a request.
  • Open a request
  • Send the request

The callback function

It’s the callback function that does all the work; it performs the action to be taken when the response from the server is sent back.

  • Check the status of the request as well as the ready state in the condition
  • statusText is property that returns default error messages if there is a problem with an AJAX request..

Each request has to be opened, and then send with special JavaScript methods and then only on a web server rather than a local hard drive.

There are 4 main examples of callback function that I think are worth sharing.

3 Examples of callback requests

EXAMPLE 1 callback function of AJAX Request

 xhr.onreadystatechange = function() {
 if (xhr.readyState === 4 && xhr.status === 200) {
 document.getElementById('ajax').innerHTML = xhr.responseText;
 }
 };

Each callback function is just that, a function attached to an event which is the onreadystatechange which the makes the function an event handler and sends back the data requested. It does this by performing the action in the code block but also by handling potential errors in the process.

Errors could be network errors like a 404 browser return which you’d get if when you try open a webpage but your internet connection has failed. This is what xhr.status is checking for. If it reaches the status code 200 then all is well and AJAX can send the request.

Example 2

 
xhr.onreadystatechange = function() {
 if (xhr.readyState === 4) {
 
 if(xhr.status === 200) {
 document.getElementById('ajax').innerHTML = xhr.responseText;
 
 } else if (xhr.status === 404) {
 
 } else if (xhr.status === 500) {
 }
 }
 };

This example does everything the first one does but goes a little deeper. It specifically searches 404 error or a 500 error code and the gives code blocks where actions can be taken. Typically this would be an error message returned to the browser indicating what has gone wrong.

But this method can be a little laborious because you have to make an else if condition for every error message you can think of.

Luckily there is a way that you can make AJAX do most if not all of the legwork for you.

EXAMPLE 3 callback function of AJAX Request

 xhr.onreadystatechange = function() {
 if (xhr.readyState === 4) {
 
 if(xhr.status === 200) {
 document.getElementById('ajax').innerHTML = xhr.responseText;
 
 } else {
 document.write(xhr.statusText);
 }
 
 
 };

The above example introduces something called a statusText variable, that stores all the error responses for you and display them as an error message for you to read. It’s probably better to put this in an alert message as this doesn’t affect what is already on the screen. But I prefer putting it in a document.write method.

Unfortunately, this has the drawback of replacing the entire contents of the screen with the single error message. And it’s a little bit vague having just the error message with no way of returning to the original page (barring the browser back button).

So I dug a little deeper and created this little snippet, using JavaScript to make it a bit more user-friendly.

 document.write("Sorry the page you attempted to request was " + xhr.statusText + " <a href = \"http://www.jonniegrieve.co.uk/jg-lab.co.uk/index.html \">Click here</a>" + " To go back");

To make sure all the link is recognised by the browser as a HTML browser tag \ escape characters are used so it remains part of the string and the quote marks don’t break up the string.

Snippet: 

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
xhr = document.getElementById(“sidebar”).innerHTML=xhr.responseText;
}
};

And voilà! We have a simple to use AJAX callback function. It’s amazing to think how easy it can be to use a fantastic web technology like AJAX. It’s easier than you might think.

Balsamiq for Desktop Mockups

Today I’ve finally completed my download of Balsamiq mockups. Balsamiq Mockups is a well recommended desktop tool for wireframing websites and multimedia interfaces.

I’ve been looking for a wireframing tool for some time and there are a number of solutions out there.

I’ve seen solutions by websites like Mockflow, Mockingbird, Quirktools suite of tools. Screenfly by the way is a very useful tool for Responsive design.

Some of these I’ve been very impressed with. I have to say though, not to the extent where I’ve been moved to commit to a potentially expensive monthly payment plan where I could maybe spend the money elsewhere.

In the last year, I put money towards excellent Technology tuition at Treehouse. You maybe have seen me talking about that recently 😉 but Balsamiq was a recommended purchase program by the web design course tutor Nick Pettit, so then since then it’s been on my mind to purchase this product.

Today I’ve been getting to know Balsamiq. It does everything you’d expect of a paper wireframing tool and allows me to replicate the techniques of wireframing that I applied on paper, to the digital screen.

It’s a digital representation in every way of sketched interface elements you’d find on paper.

balsamiq-blog

All the tools you need are provided by easy drag and drop placement from a menu on the top, from interface elements to layering.

If you need something to represent an icon or call to action element, drag and drop it.

If you need something to represent a search box, drag and drop it.

or if you need to factor in form controls they’re available too.

balsamiq-blog2

The above image shows an example of a setup I put together in one of my first mockups.  In my early years, I used a lot of paper to do my wireframes.  There’s a still a lot to be said for for wireframing with pencil and paper and this is not something I’d argue against.

But with a bit of effort into putting together an early example of wireframe sheet with spaces for outlining a design colour palette, project information and any design notes that come to mind during the wireframe process.  This product takes away most if not all of the legwork people whose don’t perhaps have the drawing skills with the pencil that others may possess. Like me for instance.

You can make such a template document by clicking a simple “clone” button in the file menu to take what’s already in the file and start with a fresh mockup file.  Just the same as opening a Microsoft Word template file.

For ease of use and ultimate customisation, Balsamiq takes many queues from authoring applications such as Photoshop with all the options you’d expect from a authoring program the form of a familiar  (Heads Up Display) HUD.

You can even save your wireframes as an XML file so and pass it on to other Balsamiq users by importing them to their screens.

It’s still early days but the investment is looking like a good one and I’m looking forward to learning to make the most of what Balsamiq has to offer

Understanding Floats in CSS

In my first blog of 2015, I wanted to talk about CSS floats. One of the things about my way of learning is that I learn coding mostly by doing.

By doing, I’ve learned that HTML elements can’t be placed just anywhere on a page. They have to interact with something, whether it be be the parent element of a page, or another adjacent element. Each new element becomes another branch on the so called HTML tree or in other words the Document Objecr Model (DOM).

So what if I want an element that’s closely linked semantically to another to appear side by side rather than the default positioning of top to bottom?

Before I knew anything about CSS Floats at all, I used to do this by painstakingly positioning an element “absolutely” with something like this.

position: absolute;

“Brilliant!” I thought. Now I can position an element exactly where I want it, down to the single pixel. Except these days that is no good for responsive design.

Later on I cottoned on to Floats. By for example, applying a float: left; CSS directive to an element, elements around it would shoot up the page and suddenly we have content stacked in columns. One problem solved, but then woah, where do the rest of the elements go? What’s with the overlapping of the element to the rest of the page?

I understood what floats did practically but never really got behind what the were really doing until now and why the rest of the page would react the way they do.

Example

I created a page today with a div element that contains two other divs currently stacked on top each other. Rather than a border, I’ve enclosed them with an old school <hr> element blow it to separate the content.

float-blog-image

I created a little page today that I hope will confirm to me what I now understand about floats. About how they take elements out of normal document flow i.e. left to right rather than top to bottom. About how they cause layout issues with elements not floated; how they wrap around float elements and how to fix these layout issues.

The code above is represents the page as it is before any floating takes place. I also separated the box elements in the CSS code so I could demonstrate each one with their own float settings.

float: left and float right;

The above CSS rules float an element out of normal flow and give it a positioning property relative to its containing element. This can cause some unwanted layout issues such as elements wrapping and text spillng anywhere it can between floated elements. Or it might cause elements beneath to overlap each other.

Elements like this paragraph which I added to the code to test how it would react to the floated elements above it.

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mollis nunc
eu libero mollis, vel rhoncus nunc tristique. Integer suscipit lorem a felis ultrices,
nec pharetra nisl molestie. Sed dignissim condimentum diam, sit amet.</p>

There are a few ways to get around this issue. One of these ways to dynamically create space or content with a clearfix, filling in the space where floated elements take it.

.clearFixClass {
content: “”;
display: table;
clear: both;
}

The clearfix contains the CSS rule clear which accompanies the float; clearing the floats on either side of the containing element. It also fills the element assigned to it with empty space so it’s recognised by the browser as an element with its original width and height, almost as it the element wasn’t floated at all.

In this example, one clearFix goes on the containing element, in this case div with the class of .container. You can then apply the .clearFixClass rule to any other elements that are not displaying as you’d like. When you apply the class to the first paragraph below the boxes, it shifts it directly below, just as it was before, one element on top of the other now that there’s no longer any floated elements.

Conclusion

Floated elements were always a simple concept to understand. It’s merely a case of taking elements out of normal flow so you can create columns of content. All you need is a clearfix solution to fix your layout so you can make sure your elements layout correctly and put back in normal flow as if no floating happened at all and you can create more complex web interfaces.