AJAX (reading)
The 4 main steps of AJAX
- DOM (Document Object Model) Event Occurs
- An interaction occurs on the webpage (#div link or button is clicked)
- The JS running on the page has an event listener for the interaction
$("#new-fortune").on("click", function(event) {
event.preventDefault()
prevents the page from executing the button/link's function within the event listener function
- The HTTP Request Occurs through AJAX
- The request is made through AJAX
- This will communicate to your server which should have a path
/new-fortune.json
in existence
var request = $.ajax({
method: "GET",
url: "/new-fortune.json"
});
- The HTTP Response returns with the JSON Payload
- The response from the server should be defined as JSON (JS Object) using
content_type :json
- A ruby hash can be converted to JSON using the
.to_json
method.
get "/new-fortune.json" do
content_type :json
{ fortune: random_fortune }.to_json
end
- Use the JSON and JQuery to update the DOM
- JQuery is a "Write Less Do More" JS Library, syntax denoted by
$
- Use
request.done
to begin the JQuery execution. - Use JQuery to manipulate the DOM, or change the page, accordingly.
request.done(function(newFortune) {
$("#fortune").text(newFortune["fortune"]);
});
AJAX and REST (reading)
- Each CRUD Action is tied to an HTTP Verb, denoted with a
.json
at the end of the path.
-
Read/Get (Already talked about in the AJAX article)
-
Create/Post
- Requires the "POST" method instead of the "GET" method
- Also requires data to be passed into the request using another argument in the request.
var fortune = { content: "Walk through life like a badass." };
var request = $.ajax({
method: "POST",
url: "/api/v1/fortunes.json",
data: fortune
});
request.done(function() {
alert("New fortune accepted");
});
Fortune.create
will allow the fortune passed in from data to persist in a csv file- The DOM Manipulation uses the
.append
method to add new content to the page.
request.done(function() {
$("ul.fortunes").append("<li>" + newFortuneContent + "</li>");
$('#fortune-content').val("");
});
- AJAX Update/PUT/PATCH
- The url must pass in an existing fortune ID, as well as data with which to update the fortune
- AJAX Destroy/DELETE
- The url must also contain the ID of an existing fortune/item
.remove
can be used to remove an html element from the page
Random Brussels Sprouts (exercise)
In the Javascript:
- Add event listener to the link on the page (#get-dish) (provided)
- Add event.prevent_default at the beginning of the listener (provided)
- Add AJAX Call to retrieve a dish from the
'/dishes/random.json'
path
In the server.rb file:
- Use
.sample
to retrieve a random dish - Create a hash using the random dish, and return it in the method as a json using the
.to_json
method
Back in the Javascript:
- Use the .done function on the AJAX request to take in the response dish and use the
.alert
function to create the alert