Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
188 lines (121 sloc) 12.1 KB

LESSON: jquery-ajax-delete


2018-06-15

Tags: javascript, jquery, ajax, HTTP, CRUD, DELETE

OBJECTIVES

By the end of this, developers should be able to:

  • Make HTTP requests using curl and AJAX to:
  • Delete a specific resource.

Use response data in future requests.

VOCABULARY

Client: A computer or program running on a computer that requests data from a server. Examples of clients we commonly use are your browser which makes request for website data, then renders the recevied data as a webpage, curl requests in bash which allow any kind of HTTP request to be made from the command line, and eventually, your scripts will also be clients, making their own requests for data from a server when approriate.

Server: A computer or program runnning on a computer that receives requests from clients and sends back responses with include the data being requested by the client. Examples of servers we commonly use are all the website addresses we visit to see webpages which we make requests to by entereing their URL into our browsers, APIs such as the Google Apis which allow us to get and modify Google App Data such as Google Maps view, Google Drive files etc, and eventually, a program you will run on your machine to serve data to your frontend client.

HTTP: HyperText Transfer Protocol – a set of standards for clients to send requests to servers and for servers to send back response data. This is how all machines communicate over the internet, on local networks, and sometimes even between different processes running on your own machine.

CRUD: Create Read Update Delete – English-language verbs formed into an acronym that let us easily remember the most common types of actions/verbs a client wants use to interact with a server. The actual action verbs included in HTTP requests to servers are named somewhat differently, but they don't form a nice acronym, therefore we have CRUD.

Request: A communication from a client to a server, asking the server to do something with the server's data, which is often stored in a database attached to the server. An HTTP request always includes the HTTP verb for the request, the resource location on the server that the client wants to make the request to, and possibly other data required for the request (for example, a request that wants to add new data to the server database will need to include this data in the request).

Response: A communication from a server to a client in response to a client request. What this data is depends both on what type of request was made, whether or not the request was successfully processed, and response data who's form and contents are determined by whoever wrote the server. All server responses come with a response code, which easily allows us to tell if the request was even succesful, and if not, what exactly went wrong.

HTTP Verb: The action word included in every HTTP client request that tells the server what exactly the client is trying to do to the server's data. Here are some common HTTP verbs.

HTTP Response Code: A 3 number code ranging from 100 to 599 included in a server response that tells the client if their request was succesful or not, and if not, what generally went wrong. Also called HTTP status codes. Here is a list of common HTTP response codes.

URL: Uniform Resource Locator – the address on a server where data a client wants to interact with can bes accessed. Every time you got to a webpage, you go to a URL that identifies the server and the location of a resource on the server. Here is a great blog about breaking down a URL into it's parts. It's important to note that a URL is a necessary part of any HTTP request, telling the server exactly what part of the server data the client wants to interact with.

Resource: One piece of data located on a server which can be accessed by making an HTTP request including the URL of that resource, the approriate HTTP Verb, and any additional data that may be required for that request. Example: data about a single person in a server that serves address book information.

Resource Collection: The same as a resouce, but instead of a single piece of data, it is the entire colletion of data of a certain type. Extending the example above, the whole collection of all people in the address book would be a resource collection.

Database: A program / file system that allows storage of data in an effecient, safe, and scalable way, hopefully 🙃. Servers are often attached to databases which allows them to access, store, and modify data in response to client requests.

DELETE: An HTTP verb that allows a client to request that existing data on a serve be deleted. Such a request must include data to identify which data should be deleted.

API: Application Programming Interface – the standards defined by the designed of a server that tell clients how to interact with the resources of that server. APIs allow us to interact with serves without having to know anything about the "guts" of how the server actually works internally. APIs should be well documented and follow REST standards, which are a set of defined patterns and standards for how web APIs are desgined.

Ajax: Asynchronous Javascript and XML – Web development techiniques that allows a client to interact with a server asynchronously and receive data formatted in an easily digestable format. Traditionally, this formal was XML, but most dat these days is sent in requests and received in responses in JSON format, as it is easily digestable (convertable) to Object data in most programming languages.

Asynchronous/Synchronous processes: Synchronous processes are ones that execute commands (or lines of code), line by line, always waiting for a command/line to finish executing before executing the next command/line. Asynchronous processes are ones that can fire off several processes that may take different ammounts of time to execute, and instead of waiting for them all to complete, they can continue running other commands/lines, and be able to handle the returned data when those initial processes finish executing. Asynchronous requests can be very useful when making HTTP requests from your client, because you often don't know how long your request will take to complete, and you also don't want to stall out your app waiting for the response. Asynchronous requests are also useful because you can ask multiple servers for data pretty much all at once, instead of one at a time.

jQuery: A JavaScript library designed to simplify the client-side scripting of HTML. jQuery was introduced back in the bad old days of early Javascript when DOM manipulation and other tasks were much harder to pull off using just the core JS functionality. jQuery met the need of developers to be able to interact with web pages and make HTTP requests using simpler, more concise code. Since jQuery was introduced, core JS has been updated significantly to include a lot of nice features that jQuery originally created, so you can get most things done without jQuery if you want these days, but jQuery does still provide excellent cross-browser compatibility of your code, and it's still used in tons of webpages so it is essential to understand how it works.

NOTES

  • Remember that browsers are simple clients that are only concerned with GETting data and rendering it. They cannot do any other type of request, including DELETE.

  • A DELETE request must always include:

    • the URL for the resource you are trying to interact with
    • the DELETE verb
    • data to identify the actual resource (data point) you want to delete
  • A DELETE request cannot be easily reversed by a client (sometimes the server admin can do this using what is called a "rollback"). Be careful with what you delete!

EXAMPLES

DELETE Using curl

  • let's break a curl request down into it's parts:

    • the bash command to be run:

    • curl
    • optional flags for the curl command:

      • --include makes sure to display the server response headers, a part of the response that shows the HTTP status code and other info
      • --request <HTTP verb> < tells the server what HTTP verb we want to use. By default, curl usese a GET request verb, but if we want to do a different type of request, we must use --request
    • curl --include --request DELETE
    • the URL of the resource we are trying to delete:

      • the protocol, in this case http
      • the domain name, or base url of the resource, in this case server.com
      • the path to the resource we are trying to delete, which tells the server exactly which resource on the server we are requesting to be deleted, in this case /path/to/resource/10. Notice how our path ends with a number, also called the resource ID, which tells our server which resource data point to delete, in this case, the one with index 10.
  • putting it all together:

  • curl --include --request DELETE http://server.com/path/to/resource/10

DELETE Using jQuery

  • notice how the jQuery ajax mehod has exactly the same data as the bash curl requests, except this time, we can run the request with JavaScript:
$.ajax({
    url: http://server.com/path/to/resource/10,
    method: 'DELETE'
})
  • jQuery's ajax method will automatically detect whether the request was successful or not and allow you to pass callbacks to special methods to handle each case

    • Successful: request got a 2xx HTTP status in the response
    • Failure: request got a 3xx - 5xx HTTP status in the response
  • we can use these special methods then and catch on the object created by using jQuery ajax to handle succesful or not succesful outcomes:

  • $.ajax({
        url: http://server.com/path/to/resource/10,
        method: 'DELETE'
    }).then(successfulCallback).catch(failureCallback)
  • what's happening here? let's break it down into parts:

    • the ajax request $.ajax({ url: http://server.com/path/to/resource/10, method: 'DELETE' }) which create an object that handles talking to the server
    • this ajax object has two special methods to handle the outcome when the server gives us a response for a request
      • then to handle successful outomes, which will then run a callback function(in our case successfulCallBack) and pass the returned server data to the callback
      • catch to handle failure outomes, which will then run a callback function(in our case failureCallBack) and pass the returned server data to the callback
  • often times, methods that are chained to an object (ie Object.method.method2.method3), are split onto separate lines for readability:

  • $.ajax({
        url: http://server.com/path/to/resource/10,
        method: 'DELETE'
    }).then(successfulCallback)
      .catch(failureCallback)
  • and lastly, let's define some actual callback functions and see what we would get in the case of a success or a failure:

  • const successfulCallback = data => {
        console.log('Successful Delete!')
        console.log('Here is what the server said:')
        console.log(data)
    }
    
    const failureCallback = error => {
        console.log('Delete Failed!')
        console.log('Here is what the server said:')
        console.log(error)
    }
  • then we run our ajax request:

  • $.ajax({
        url: http://server.com/path/to/resource/10,
        method: 'DELETE'
    }).then(successfulCallback)
      .catch(failureCallback)
    
    /* 
    if we run this and it fails, we might get:
    */
    
    // LOGS:
    // "Delete Failed!"
    // "Here is what the server said:"
    // { status: 500, errorMsg: "DELETE request failed on the server" }
    
    
    /* 
    if we run this and it succeeds, we might get:
    */
    
    // LOGS:
    // "Successful Delete!"
    // "Here is what the server said:"
    // { status: 200, msg: "DELETE request was successful" }