Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. function attachEvents() {
  2. const kinveyAppId = "kid_S12g5Xa8W";
  3. const serviceUrl = "https://baas.kinvey.com/appdata/" + kinveyAppId;
  4. const kinveyUsername = "peter";
  5. const kinveyPassword = "p";
  6. const base64auth = btoa(kinveyUsername + ":" + kinveyPassword);
  7. const authHeaders = {"Authorization": "Basic " + base64auth};
  8.  
  9. $('#btnLoadPosts').click(loadPostsClick);
  10. // ---------------- Edited ----------------
  11. // ('#btnViewPosts').click(viewPostClick); to ('#btnViewPost').click(viewPostClick);
  12. // ID of button was wrong
  13. $('#btnViewPost').click(viewPostClick);
  14.  
  15.  
  16. function loadPostsClick() {
  17. let loadPostRequest = {
  18. method: "GET",
  19. // ---------------- Edited ----------------
  20. // when making a GET request to kinvey, it should never end with '/'
  21. // changed url: serviceUrl + "/posts/", to url: serviceUrl + "/posts",
  22. url: serviceUrl + "/posts",
  23. headers: authHeaders
  24. };
  25. $.ajax(loadPostRequest)
  26. .then(displayPosts)
  27. .catch(displayError)
  28. }
  29.  
  30. function displayPosts(posts) {
  31. $('#posts').empty();
  32. for (let post of posts) {
  33. $('#posts').append($('<option>').text(post.title).val(post._id))
  34. }
  35. }
  36.  
  37. function viewPostClick() {
  38. // ---------------- Edited selectedPostID----------------
  39. // $('#posts').val(); to $('#posts option:selected').val();
  40. // now the postID is only the ID of the selected option element
  41. let selectedPostID = $('#posts option:selected').val();
  42. if (!selectedPostID) {
  43. return;
  44. }
  45.  
  46. let requestPost = $.ajax({
  47. method: "GET",
  48. url: serviceUrl + "/posts/" + selectedPostID,
  49. headers: authHeaders
  50. });
  51. let requestComments = $.ajax({
  52. url: serviceUrl + `/comments/?query={"post_id":"${selectedPostID}"}`,
  53. headers: authHeaders
  54. });
  55.  
  56. Promise.all([requestPost, requestComments])
  57. .then(displayPostWithComments)
  58. .catch(displayError);
  59. }
  60.  
  61. function displayPostWithComments([post, comments]) {
  62. $('#post-title').text(post.title);
  63. $('#post-body').text(post.body);
  64. $('#post-comments').empty();
  65.  
  66. for (let comment of comments) {
  67. $('#post-comments').append($("<li>").text(comment.text))
  68. }
  69. }
  70.  
  71. function displayError(err) {
  72. let errDiv = $('<div>').text("Error: " + err.status + " (" + err.statusText + ")");
  73. $(document.body).prepend(errDiv);
  74. // ---------------- Edited ----------------
  75. // removed timeout, due to judge timer
  76. }
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement