Skip to content

Instantly share code, notes, and snippets.

@cmkoller
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmkoller/7308db038ff756bde24c to your computer and use it in GitHub Desktop.
Save cmkoller/7308db038ff756bde24c to your computer and use it in GitHub Desktop.
JS Systems Check Review

Systems Check Review - Javascript, jQuery, & Ajax

1. Make sure nothing runs until it all loads

window.onload = function() {

}

Alternatively, we can use the jQuery syntax:

$(document).ready(function() {

});

2. Make an event listener for when the "New Option" form submits

$('#new-option-form').on("submit", function(event) {

}

3. Prevent the default behavior from happening

event.preventDefault();

4. Get the text that the user wrote

var new_option = $('#new-option-field')[0].value;

5. Check to make sure the user actually typed something

if (new_option.length > 0) {

}

6. Call a (currently nonexistant) function to submit the option to our server.

if (new_option.length > 0) {
  submitNewOption(new_option);
}

7. Define a function that submits the new option

var submitNewOption = function(option) {

}

8. Write an ajax call that makes a post request with the relevant information

var submitNewOption = function(option) {
  $.ajax({
    method: "post",
    url: "/new_option", 
    data: { option: option }
  });
} 

9. Add a function on the end that specifies what happens when the request gets successfully completed

$.ajax({
  method: "post",
  url: "/new_option", 
  data: { option: option }
}).success(function() {
  // do stuff here
});

9. Fill out the function that specifies what happens upon a successful completion of the ajax request.

This will involve using JS to add elements to the page for the new color option, since we aren't refreshing it.

$.ajax({
  method: "post",
  url: "/new_option", 
  data: { option: option }
}).success(function() {
  alert("Success!");
  
  $('#new-vote-form').prepend(
    "<label for='choice'><input type='radio' name='choice' value="
    + option
    + ">"
    + vote_option
    + "</label><br />"
  );
  
  $('#votes-count').append(
    "<tr>"
      + "<td>" + option + "</td>"
      + "<td>0</td>"
    + "</tr>"
  );
  
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment