geoff-p2
7/27/2014 - 6:35 PM

Example of using Ajax to recreate hacker-news

Example of using Ajax to recreate hacker-news

$(document).ready(function() {
  $('.vote-button').on('click', upVote)
  $('.delete').on('click',  deletePost)
  $('form').on('submit', formSubmit );
}); // End Document Ready


function upVote(e){
  e.preventDefault();
  var url = e.target.pathname;
  var ajaxUpVote = $.ajax({
    url: url,
    type: 'GET'
  })
  ajaxUpVote.done(updateVote);
  ajaxUpVote.fail(showErrors);
}

function updateVote(data){
  var postId = data.postId;
  $('#' + postId + ' a.vote-button').css('color', 'red')
  $display_total = $('#' + postId + ' .points')
  $display_total.text(data.voteCount)
}

function deletePost(e){
  e.preventDefault();
  var url = e.target.pathname;
  var ajaxDelete = $.ajax({
    url: url,
    type: 'DELETE'
    })
  ajaxDelete.done(deletePostFromView)
  ajaxDelete.fail(showErrors)
}

function deletePostFromView(data) {
  $('#' + data.postId).remove()
}

function formSubmit(e){
  e.preventDefault();

  var ajaxPost= $.ajax({
      url: "/posts",
      type: 'POST',
      data: $('form').serialize()
      })
  ajaxPost.done(addPostToView)
  ajaxPost.fail(showErrors)
}

function addPostToView(data) {
 $('.post-container').append(data)
}

function showErrors(jqXHR, textStatus, errorThrown){
  $('page').attr('placeholder', "VALUE CANT BE BLANK")
}