Skip to content

Instantly share code, notes, and snippets.

@ciacci1234
Last active March 16, 2018 00:32
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 ciacci1234/dcc40d6df123c66b497dd201b4a24cc2 to your computer and use it in GitHub Desktop.
Save ciacci1234/dcc40d6df123c66b497dd201b4a24cc2 to your computer and use it in GitHub Desktop.
AJAX'ing the user's ability to bookmark(favorite) resources to his profile page.

Lessons Learned

  • Wiring together a feature relying on AJAX.*
  • Solidified my understanding of MVC concepts.

Context

This is code from my first full-stack web application built in the final week of DevBootcamp a 5-month web development bootcamp I attended. I and four others built a meditation app for beginners that presented meditations from a variety of spiritual traditions, reminded users daily of the time they committed to the meditation, and tracked their progress along the way.

My main responsibilities included building out the practices and resources pages. The code above pertains to the bookmark functionality on the resources page, so users could save their favorite resources that supplemented their chosen meditation practice.

*The code below's fairly straightforward AJAX code utilizing jQuery and the correlating view file, but it was one of the first features for a web application which I built with little guidance from teachers or peers, and so I have fond memories of tinkering around with this to get bookmarking functional.

//This is code can be found at ciacci1234/the-still-life/app/assets/javascripts/bookmarks.js
$(document).ready(function() {
$(".bookmark-form").submit(function(e) {
e.preventDefault();
target = $(e.target)
$.ajax({
url: target.attr('action'),
method: 'post',
data: $(target).serialize()
})
.done(function(response){
$(target).parent().replaceWith(response)
})
});
});
//The response replaces HTML form represented by empty heart icon with a filled-heart icon, indicating to the user that the resource
//was successfully bookmarked to their profile page. View file code show below:
<h2> Readings </h2><br>
<% @resources.readings.each do |reading| %>
<p><%= link_to reading.name, reading.url, class:'resource-link' %></p>
<p><%= reading.description %></p>
<% if @current_user %>
<% if @current_user.bookmarks.where(resource: @resources.find_by(name: reading.name ) ).length == 0 %>
<div class ='bookmark-form' id="resource-<%=reading.id %>">
<%= form_for @bookmark, :class => "form-heart" do |f|%>
<%= f.button :submit, class: "submit-with-icon" do %>
<i class="glyphicon glyphicon-heart-empty" aria-hidden="true"></i>
<% end %>
<%= hidden_field_tag 'resource_id', reading.id %>
<% end %>
</div>
<% else %>
<i class="glyphicon glyphicon-heart" aria-hidden="true"></i>
<% end %>
<% end %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment