Skip to content

Instantly share code, notes, and snippets.

@dreamorosi
Last active December 11, 2017 21:09
Show Gist options
  • Save dreamorosi/3d95c71057d66fc0847b1c5c0f1d021b to your computer and use it in GitHub Desktop.
Save dreamorosi/3d95c71057d66fc0847b1c5c0f1d021b to your computer and use it in GitHub Desktop.

Assignment 2

So the assignment consists of two main tasks:

  • Send to this API http://www.winelove.club/doc/html/testRestApi.php a json object containing all the data which have been typed inside your landing page web form, using Javascript + Ajax.
  • Create a dynamic list content in your personal project reading data from a locally stored json using Javascript + Ajax.

While doing the assignment you should also remember to:

  • Work on your local project and keep track of the changes with git.
  • Remember to start (npm start) or stop (ctrl + C) Sass while if you're making changes to the style/layout.
  • Indent your code in a consistent way.
  • Leave comments in the code whenever is needed.

Let's now look at both tasks more in depth, I'm gonna start from the second one since it's easier and you probably already have some of it done.

Task 2

Create a dynamic list that at first is empty but as soon as the page loads a JSON file gets loaded (via $.ajax()) and its content is used to fill the list. Now I know that he talks about a list but in the pdf of the assignment he shared with us he says that the goal of this assignment is to show "your capability to develop a dynamic web page parsing and sending json objects using all the concepts that you have learnt so far “, that means you just have to show him that you can load data from a JSON file and use it to dynamically change the content of the page.

An easy example would be to start from a JSON file like this

{
  "countries": [
    {
      "code": "US",
      "name": "United States"
    },
    {
      "code": "CA",
      "name": "Canada"
    },
    {
      "code": "MX",
      "name": "Mexico"
    },
    {
      "code": "AI",
      "name": "Anguilla"
    }
  ]
}

and also have a <select> like this in our html page:

<select id="countries">
  <option value="" selected>Select a country</option>
</select>

Let's also assume you're already using jQuery in your page (that means you have the file somewhere and you're linking it to the page before the link to your script.js file). The steps you have to take to read the content of the JSON file and populate the select are the following:

  • Make sure that everything we're about to do gets done only after the page is fully loaded.
  • Select the select from the page and store it in a variable.
  • Create an $.ajax() call that reads the file.
  • When the ajax call is done the returned data should be available (test it with console.log()).
  • Append the data into the select.

So for the first step all we have to do is to make sure that everything we write is inside the jQuery ready event like so:

$(document).ready(function(){    
  // The rest of your code goes here   
});

Then you just have to create a variable and assign to it a reference to the HTML element, in this case you want to get the select from the page we saw before using its id:

var mySelect = $('#countries');

Once you have all set and working you have to make the ajax call that actually reads the file:

// Part 1
$.ajax({
  dataType: 'json',
  type:'GET',
  url: "PATH_OF_YOUR_JSON_FILE"
})
// Part 2
.done(function(data){ 
  console.log(data);
})
// Part 3
.fail(function(er) {
  console.log('error', er);
})

The important stuff about this call are three:

  • The first one is the actual ajax call that contains the settings that are gonna be used to make the call, here we have dataType that states what kind of data we're expecting back, type that states what kind of call we're making and url that is the url (or location) where from we're attempting to read stuff, here you'll have to put the destination of your json file. You can also read more about these paramenters and the others available here.
  • The second part gets executed only when the ajax call from the previous step is complete and also successful (meaning that there wasn't any error), here we're just logging the data to test that everything's working as supposed to. The name of the variable data in the function(data) and console.log(data) is made up, it could be anything since we're just saying something like when the ajax call is done put its result (returned data) into a variable called data so I can use it later inside the function body.
  • The third part instead gets executed if and only the ajax call is complete but an error occurred, usually all you do is console.log() the error.

Now that we're loading our stuff from the JSON file and we have it in the script we can easily append it into the actual page, we can do that like so (we're gonna work in the Part 2 from the previous example):

// Part 2
.done(function(data){ 
  console.log(data);
  // New code
  var optionsToBeAppended = "";
  var countries = data.countries
  $.each(countries, function(key, value) {
    optionsToBeAppended = optionsToBeAppended + '<option value="' + value.code + '">' + value.name + '</option>';
  });
  mySelect.append(optionsToBeAppended); 
})

The idea is that since we're loading a JSON file that contains an array called countries that is iterable so we can go through all its elements and do stuff with them. We're using $.each() from jQuery that is essentially a fancy for loop. At each iteration we read one value of the countries array and we create a string containing the markup of an option, if you don't understand what's going on try to put a console.log(value) inside the $.each() and see what happens. We're also using the mySelect that we created before and we're appending the options inside it after we have created the markup.

Now your page should show a select with countries inside it, to explain this task I used as reference these two examples from the teacher BTS_2018/03_Jquery/26_ajax.html and BTS/03_Jquery/27_ajax_foreach.html that you can find on Bitbucket.

If you think about it you have this exact same functionality in the modals of the index.html page, the only difference is that you load the data from an array inside the script instead of loading it from an external file. Also, if I'm not wrong you already did something like this for a table with different kinds of sharks so if that is still working it should be more than enough.

Task 1

This task is a little bit more tricky since it involves an external API but the concepts involved are similar to the previous one. You have to create a form that when submitted sends the informations typed into the form to an API. The API expects a JSON object and should return back the same object. You do that by creating a function (i.e. formSubmit()) that gets called onsubmit, this function gets the value of each input element (i.e. let’s say you have a variable that contains the HTML element like this var emailField = $(‘#id_of_the_field’), you can get its value by doing emailField.val()). When you have all the values you just have to put them in a JSON object (not an external file, a JSON object is just a normal Object like the ones you have on Codepen from your book) and then send them via $.ajax() to the API. Inside the .done() function of the ajax call you can just console.log() the result or show an alert() that says that the form has been submitted.

So you need a page with a form and both jQuery and your script file linked to it:

<form id="contactForm">
  <label for="nameField">Full Name</label>
  <input id="nameField" type="text" required />
  <label for="emailField">Email</label>
  <input id="emailField" type="email" required />
  <label for="messageField">Message</label>
  <textarea id="messageField" required></textarea>
  <button type="submit">Send</button>
</form>

Our script instead is gonna look like this for the reasons we saw before:

$(document).ready(function(){    
  // The rest of your code goes here   
});

What we have to do now is:

  • Select the form from the page and append an event listener that calls a function when the form is submitted.
  • Prevent default behavior (refresh page) inside the called function.
  • Select and read the value of each field inside the called function.
  • Create a JSON object with the values that we're gonna send.
  • Make an ajax call to the endpoint sending the JSON object as data.
  • Show something to tell the user that the action was successful (or wasn't).

So at first we want to select the form from the page and tell it to call a specific function when its submitted.

$('#contactForm').submit(processForm);

function processForm () {
  alert('Form submitted');
}

We are selecting the form element from the page using jQuery and its id as identifier and then we're saying whenever the form we just selected is submitted call a function called processForm() that we created somewhere else in the file. The processForm() function currently only shows an alert, the problem is that the page gets refreshed every time and we don't want that.

That brings us to the next step, preventing the page refresh. All we have to do to make it work (or should I say stop refreshing) is to pass the event e as parameter and call the preventDefault() method on it.

function processForm (e) {
  e.preventDefault();
  alert('Form submitted');
}

Now that the function gets called and the page doesn't refresh we can focus on reading the values of the fields inside the form:

function processForm (e) {
  e.preventDefault();
  var fullNameValue = $("#nameField").val();
  var emailValue = $("#emailField").val();
  var messageValue = $("#messageField").val();
  console.log(fullNameValue);
  console.log(emailValue);
  console.log(messageValue);
}

As you can see we are creating one variable for each field and we are selecting the element using jQuery and its id as identifier, in the meantime we're also reading its value (what is written inside the field) using .val(). Then, just to test that everything is working we are logging the values inside the console.

Once we have all the values working we need to structure them inside a JSON object that will be passed to the API through the ajax call, as we did before we're also gonna log it into the console to test it:

function processForm (e) {
  e.preventDefault();
  var fullNameValue = $("#nameField").val();
  var emailValue = $("#emailField").val();
  var messageValue = $("#messageField").val();
  
  var dataToBeSent = {
    "fullName": fullNameValue,
    "email": emailValue,
    "message": messageValue
  }
  console.log(dataToBeSent)
}

Next thing we have to do is to create the actual ajax call to the API and send the data, we can use the same things we saw for the previous task so I'm not gonna go in details this time:

function processForm (e) {
  var dataToBeSent = {
    "fullName": fullNameValue,
    "email": emailValue,
    "message": messageValue
  }
  // Code from previous example
  
  // New code
  $.ajax({
    'dataType': 'json',
    'type':'POST',
    'url': "http://www.winelove.club/doc/html/testRestApi.php",
    'data': {obj: JSON.stringify(dataToBeSent)}
  })
  .done(function(data){ 
    console.log(data)
    alert("Form sent successfully");
  })
  .fail(function(er) {
    console.log('error', er);
    alert("An error occurred, sorry!");
  })
}

We're also logging the data we get back from the API and showing an alert for the user to let her know that something happened.

For this task I used as example the stuff shown by Andrea in the BTS_2018/04_AJAX/js/main.js and 03_Jquery/examples/04_form/index.html files that you can find on Bitbucket.

Important

I made this document to try to help you, if something is broken, wrong or you have better solutions go for them! Also I didn't use any of this code but copied it from Andrea's examples, that means you're free to use it but maybe consider making the effort to change it a little bit (like function names, variables, order and stuff like that) so that they don't all look the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment