Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
175 lines (127 sloc) 6.26 KB

LESSON: jquery-ajax-patch


2018-06-18

OBJECTIVES

Make HTTP requests using curl and AJAX for:

  • Altering a specific resource.

VOCABULARY

PATCH: A PATCH request is a type of HTTP request that let's us change part of an existing resource's data on a server. PATCH allows us to update one or more values by key for a given resource. Patch requests must include an ID to identify a resource (usually a positive integer at the end of the path in the URL) and the key value pairs (as JSON) for the data you want to change sent along as data in the request. PATCH is not idempotent (see below for definition)

PUT: A PUT request is a type of HTTP request that let's us replace all of the data of an existing resource on a server. PUT requires us to send data that matches the "shape" (see below for definition) of the data in the server resource. Unlike PATCH, PUT is idempotent (see below for definition)

Object Shape: The shape of an object is a way of representing the structure of an object and the types of values per key in the object, without requiring the exact values within the object. For every key in an object, the shape of the object can be thought of as a list of the key names in the object, and the expected data type per key (Number, String, List/Array etc).

Idempotent: Idempotent describes any process which after makinng changes to data, always has the exact same result. When you make a PUT request, no matter what the starting state of the resource, the result will always be exactly the same. However, since PATCH only updates some of the keys in the resource, the result of a PATCH request may vary from request to request as the other keys not altered by PATCH may have changes between requests.

Form Validation: When forms are submitted, the data in the various input fields are checked that they meet certain requirements (ie emails should be a string without spaces, and @ symbol, and another string without spaces, etc). This can help prevent the user sending data that is wrongly formatted / not entered correctly in a HTTP Request by asking them to fix input data in the form before the form can even be submitted.

NOTES

  • The steps for this lesson resemble those for the DELETE and GET lessons, except we are also adding form validation steps as well as sending data with our HTTP request.

EXAMPLES

Form Validation

  • given this form HTML for a form that will update existing book data for a particular book:

  • <h2>Update One Book</h2>
    <form class="books" 
          id="book-update">
        <div class="form-group">
            <input type="text" 
                   name="book[id]" 
                   id="book-id-update"
                   placeholder="Resource ID Here">
            <input type="text" 
                   name="book[title]"
                   placeholder="Resource Title Here">
            <input type="text" 
                   name="book[author]"
                   placeholder="Resource Author Here">
        </div>
        <button type="submit" 
                class="btn btn-default">Update</button>
    </form>
  • and here is form validation for each form element to make sure they were entered:

  • const data = getFormFields(event.target)
    const book = data.book
    
    // if title is blank
    if (book.title === '') {
        $('#content').html('<p>Title is required</p>')
        return false
    }
    
    // if id is blank
    if (book.id.length === 0) {
        $('#content').html('<p>Book ID is required</p>')
        return false
    }
    
    // if author is blank
    if (book.author === '') {
        $('#content').html('<p>Author is required</p>')
        return false
    }
    • notice how this will make sure that none of the data is empty in our form, so that the data that is eventually sent via an HTTP PATCH request doesn't have any empty values

PATCH request

  • if we entered the following data into our form:

    • id: 4
    • title: "A New Title"
    • author: "me"
  • notice how the values for each input are not empty, so that our form validation will succeed and allow for the request to be sent

  • getFormFields will automatically compile our form data into an object that looks like:

  • {
        book: {
            id: 4,
            title: "A New Title",
            author: "me"
        }
    }
  • then, we can use this data in our actual HTTP PATCH request (called update here) as follows:

  • const update = function (data) {
      return $.ajax({
        url: config.apiUrl + '/books/' + data.book.id,
        method: 'PATCH',
        data
      })
    }

How getFormField Helps Us Send HTTP data

Server Side

  • We have set up a Libray server that wants PATCH request data in a particular format:

    URL
    Verb URI Pattern
    PATCH /books/:id
    DATA (as curl)
    curl --include --request PATCH "https://wdi-library-api.herokuapp.com/books/${ID}" \
      --header "Content-type: application/json" \
      --data '{
        "book": {
          "title": "'"${TITLE}"'",
          "author": "'"${AUTHOR}"'"
        }
      }'
    DATA (translated to js)
    data = {
        book: {
            title: "<your title>",
            author: "<your author>"
        }
    }
  • notice that this js version of the JSON data required for a PATCH request looks almost exactly like the data generated by getFormFields in the above section, except that id is not passed in the PATCH data, it is sent a the end of the URL (/books/:id)

Client Side

  • on our client side, the form we have made has special name attribue values for it's input elements:

  •   <input name="<resource name>[<key name>]" />
  • and getFormFields will automatically compile data from forms which have name attributes in their input elements of the following format:

  • {
        <resource name>: {
            <key name>: <value of the input>,
            ...
        }
    }
  • which then allows us to get the id out of the data object to add to HTTP request URL, and and send the rest of the values as data with the request