Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. https://github.com/vdonchev/JavaScriptApps-AllExercisesAndLabs
  2.  
  3. //students////////////////////////////
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <head>
  7.     <meta charset="UTF-8">
  8.     <title>Shit</title>
  9.  
  10.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  11.     <style>
  12.         #results {
  13.             background-color: #FFFFFF;
  14.             display: flex;
  15.             flex-direction: column;
  16.             text-align: center;
  17.         }
  18.  
  19.         #results tr {
  20.             background-color: #AAAAAA;
  21.             padding: 5vh;
  22.             font-size: 1.5vw;
  23.         }
  24.  
  25.         #results tr:nth-child(odd) {
  26.             background-color: #808080;
  27.         }
  28.  
  29.         #results tr:first-child {
  30.             background-color: #000000;
  31.             color: #FFFFFF;
  32.             font-weight: bold;
  33.             font-size: 2vw;
  34.         }
  35.  
  36.         #results tr th {
  37.             padding: 1vw;
  38.         }
  39.  
  40.         #results tr td {
  41.             padding: 1vw;
  42.             transition: font-size 0.2s;
  43.         }
  44.  
  45.         #results tr:not(:first-child):hover {
  46.             background-color: #F0F8FF;
  47.             color: #000000;
  48.             font-size: 2.25vw;
  49.         }
  50.  
  51.         .user {
  52.             background-color: red;
  53.             font-size: 1.5vw;
  54.             text-align: center;
  55.         }
  56.  
  57.         #btn {
  58.             background-color: yellow;
  59.         }
  60.  
  61.     </style>
  62. </head>
  63. <body>
  64. <table id="results">
  65.  
  66.  
  67.  
  68.     <input id="inputID" class="user" value="insert ID">
  69.     <input id="inputFirstName" class="user" value="insert FirstName">
  70.     <input id="inputLastName" class="user" value="insert LastName">
  71.     <input id="inputFacultyNumber" class="user" value="insert FacultyNumber">
  72.     <input id="inputGrade" class="user" value="insert Grade">
  73.     <button id="btn">upload</button >
  74.  
  75.     <tr>
  76.         <th>ID</th>
  77.         <th>First Name</th>
  78.         <th>Last Name</th>
  79.         <th>Faculty Number</th>
  80.         <th>Grade</th>
  81.     </tr>
  82. </table>
  83.  
  84.  
  85. <!--<script src="script.js"></script>-->
  86.  
  87. <script>
  88.  
  89.     loadStudents();
  90.     function loadStudents() {
  91.  
  92.         const appKey = "kid_BJXTsSi-e";
  93.         const baseUrl = "https://baas.kinvey.com/appdata/" + appKey + "/students";
  94.         const username = "guest";
  95.         const password = "guest";
  96.  
  97.         let authHeaders = {
  98.             "Authorization": "Basic " + btoa(username + ":" + password),
  99.             "Content-Type": "application/json"
  100.         };
  101.  
  102.         getStudents();
  103.  
  104.         function getStudents() {
  105.             $.get({
  106.                 url: baseUrl,
  107.                 headers: authHeaders
  108.             })
  109.                     .then(displayStudents)
  110.                     .catch();
  111.  
  112.             function displayStudents(info) {
  113.                 let byid = info.slice(0);
  114.                 byid.sort(function (a, b) {
  115.                     return a.ID - b.ID;
  116.                 });
  117.  
  118.                 for (let student of byid) {
  119.                     $("#results")
  120.                             .append($("<tr>")
  121.                                     .append($("<th>").text(student.ID))
  122.                                     .append($("<th>").text(student.FirstName))
  123.                                     .append($("<th>").text(student.LastName))
  124.                                     .append($("<th>").text(student.FacultyNumber))
  125.                                     .append($("<th>").text(student.Grade))
  126.                             );
  127.                 }
  128.             }
  129.         }
  130.  
  131.         $("#btn").click(function () {
  132.             let id = Number($('#inputID').val().trim());
  133.             let firstName = $('#inputFirstName').val().trim();
  134.             let lastName = $('#inputLastName').val().trim();
  135.             let facultyNumber = $('#inputFacultyNumber').val().trim();
  136.             let grade = Number($('#inputGrade').val().trim());
  137.  
  138.             $.post({
  139.                 url: baseUrl,
  140.                 headers: authHeaders,
  141.                 data: JSON.stringify({
  142.                     ID: id,
  143.                     FirstName: firstName,
  144.                     LastName: lastName,
  145.                     FacultyNumber: facultyNumber,
  146.                     Grade: grade
  147.                 })
  148.             }).then(del())
  149.                     .then(location.reload(), alert("reloaded"))
  150.                     .catch(alert("kur"))
  151.  
  152.         });
  153.  
  154.         function del() {
  155.  
  156.             $("#results tr:last").remove();
  157.         }
  158.     }
  159. </script>
  160. </body>
  161. </html>
  162. /////////////////////examPreparation//////////////////////////////////
  163. <!DOCTYPE html>
  164. <html lang="en">
  165. <head>
  166.     <meta charset="UTF-8">
  167.     <title>Title</title>
  168.     <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  169.  
  170.     <style>
  171.         #menu {
  172.             background: #DDD;
  173.             text-align: center;
  174.             padding: 5px;
  175.             line-height: 1.5;
  176.             border-radius: 3px;
  177.             overflow: auto;
  178.         }
  179.  
  180.         #menu > #loggedInUser {
  181.             float: right;
  182.             margin-right: 10px;
  183.         }
  184.  
  185.         #menu a {
  186.             text-decoration: none;
  187.             padding: 5px 10px;
  188.             border-radius: 5px;
  189.         }
  190.  
  191.         a {
  192.             text-decoration: none;
  193.             padding-right: 10px;
  194.         }
  195.  
  196.         #menu a:hover {
  197.             background: #BBB;
  198.         }
  199.  
  200.         main > section {
  201.             /*display: none;*/
  202.             padding: 20px 5px;
  203.         }
  204.  
  205.         section h1 {
  206.             margin: 10px 0px;
  207.             font-size: 1.2em;
  208.         }
  209.  
  210.         table th {
  211.             background: #DDD;
  212.             padding: 10px;
  213.         }
  214.  
  215.         table td {
  216.             padding: 5px 10px;
  217.             background: #EEE;
  218.         }
  219.  
  220.         #infoBox, #errorBox, #loadingBox {
  221.             display: none;
  222.             width: 80%;
  223.             margin: 10px auto;
  224.             color: white;
  225.             text-align: center;
  226.             padding: 5px;
  227.             border-radius: 3px;
  228.         }
  229.  
  230.         #loadingBox {
  231.             background: #7CB3E9;
  232.         }
  233.  
  234.         #infoBox {
  235.             background: #393;
  236.         }
  237.  
  238.         #errorBox {
  239.             background: #F50;
  240.         }
  241.  
  242.         footer {
  243.             background: #DDD;
  244.             padding: 5px 10px;
  245.             font-size: 0.8em;
  246.             text-align: center;
  247.             border-radius: 3px;
  248.         }
  249.  
  250.         #textAuthor, #textDescription {
  251.             margin-bottom: 10px;
  252.             background-color: white;
  253.         }
  254.  
  255.         td a:hover {
  256.             color: red;
  257.         }
  258.         #loggedInUser{
  259.             max-width:100%;
  260.             max-height:100%;
  261.         }
  262.     </style>
  263.  
  264. </head>
  265. <body onload="start()">
  266. <header id="menu">
  267.     <a href="#" id="linkHome">Home</a>
  268.     <a href="#" id="linkLogin">Login</a>
  269.     <a href="#" id="linkRegister">Register</a>
  270.     <a href="#" id="linkListBooks">List Books</a>
  271.     <a href="#" id="linkCreateBook">Create Book</a>
  272.     <a href="#" id="linkLogout">Logout</a>
  273.     <span id="loggedInUser"  ></span>
  274. </header>
  275. <section id="loadingBox">Loading ...</section>
  276. <section id="infoBox">Info</section>
  277. <section id="errorBox">Error</section>
  278.  
  279. <section id="viewHome">
  280.     <h1>Welcome</h1>
  281.     Welcome to our book library.
  282. </section>
  283.  
  284.  
  285. <main>
  286.     <section id="viewLogin">
  287.         <h1>Please login</h1>
  288.         <form id="formLogin">
  289.             <div>Username:</div>
  290.             <div><input type="text" name=
  291.                     "username" required/></div>
  292.             <div>Password:</div>
  293.             <div><input type="password"
  294.                         name="passwd" required/></div>
  295.             <div><input type="submit" value="Login" id="buttonLoginUser"/></div>
  296.         </form>
  297.     </section>
  298.  
  299.     <section id="viewRegister">
  300.         <h1>Please register here</h1>
  301.         <form id="formRegister">
  302.             <div>Username:</div>
  303.             <div><input type="text" name=   "username" required/></div>
  304.             <div>Password:</div>
  305.             <div><input type="password" name="passwd" required/></div>
  306.             <div>Picture URL:</div>
  307.             <div><input type="text" name="image" required /></div>
  308.  
  309.             <div><input type="submit" value="Register" id="buttonRegisterUser"/></div>
  310.         </form>
  311.     </section>
  312.  
  313.     <section id="viewBooks">
  314.         <h1>Books</h1>
  315.         <div id="books">
  316.             <table>
  317.                 <tr>
  318.                     <th>Title</th>
  319.                     <th>Author</th>
  320.                     <th>Description</th>
  321.                     <th>Actions</th>
  322.                 </tr>
  323.                 <tr>
  324.                     <td>Book title</td>
  325.                     <td>Book author</td>
  326.                     <td>Book description</td>
  327.                     <td>
  328.                         <a href="#">[Delete]</a>
  329.                         <a href="#">[Edit]</a>
  330.                     </td>
  331.                 </tr>
  332.  
  333.             </table>
  334.         </div>
  335.     </section>
  336.  
  337.     <section id="viewCreateBook">
  338.         <h1>Create new book</h1>
  339.         <form id="formCreateBook">
  340.             <div>Title:</div>
  341.             <div><input type="text" name="title" required/></div>
  342.             <div>Author:</div>
  343.             <div><input type="text" name="author" required/></div>
  344.             <div>Price:</div>
  345.             <div><input type="text" name="price" required/>lv.</div>
  346.             <div>Description:</div>
  347.             <div><textarea name="descr" rows="10" required></textarea></div>
  348.             <div><input type="submit" value="Create" id="buttonCreateBook"/></div>
  349.  
  350.         </form>
  351.     </section>
  352.  
  353.     <section id="viewEditBook">
  354.         <h1>Edit existing book</h1>
  355.         <form id="formEditBook">
  356.             <div><input type="hidden" name="id" required/></div>
  357.             <div>Title:</div>
  358.             <div><input type="text" name="title" required/></div>
  359.             <div>Author:</div>
  360.             <div><input type="text" name="author" required/></div>
  361.             <div>Price:</div>
  362.             <div><input type="text" name="price"/>lv.</div>
  363.             <div>Description:</div>
  364.             <div><textarea name="descr" rows="10"required></textarea></div>
  365.             <div><input type=submit value="Edit" id="buttonEditBook"/></div>
  366.         </form>
  367.     </section>
  368.  
  369.     <section id="showSelected">
  370.         <h3></h3>
  371.         <div><input type="text" id="textAuthor" disabled></div>
  372.         <div><textarea id="textDescription" rows="10" disabled></textarea></div>
  373.  
  374.  
  375.     </section>
  376.  
  377. </main>
  378.  
  379. <footer>Book Library - Simple SPA Application</footer>
  380.  
  381.  
  382. <script>
  383.     function start() {
  384.  
  385.         sessionStorage.clear(); // Clear user auth data
  386.         const kinveyBaseUrl = "https://baas.kinvey.com/";
  387.         const kinveyAppKey = "kid_HkGYRtH7x";
  388.         const kinveyAppSecret =
  389.                 "0aeea03501304ac3916d0b548db494e2";
  390.         const kinveyAppAuthHeaders = {
  391.             'Authorization': "Basic " +
  392.             btoa(kinveyAppKey + ":" + kinveyAppSecret),
  393.         };
  394.  
  395.         showHideMenuLinks();
  396.         showView('viewHome');
  397.         // Bind the navigation menu links
  398.         $("#linkHome").click(showHomeView);
  399.         // Bind the form submit actions
  400.         $("#formLogin").submit(loginUser);
  401.  
  402.         function showHideMenuLinks() {
  403.             $("#menu a").hide();
  404.             if (sessionStorage.getItem("authToken")) {
  405.                 //logged in user
  406.                 $("#linkHome").show();
  407.                 $("#linkListBooks").show();
  408.                 $("#linkCreateBook").show();
  409.                 $("#linkLogout").show();
  410.             }
  411.             else {
  412.                 //no user logged
  413.                 $("#linkHome").show();
  414.                 $("#linkLogin").show();
  415.                 $("#linkRegister").show();
  416.             }
  417.         }
  418.  
  419.         function showView(viewName) {
  420.             // Hide all views and show the selected view only
  421.             $('main > section').hide();
  422.             $('#' + viewName).show();
  423.         }
  424.  
  425.         function showHomeView() {
  426.             showView("viewHome")
  427.         }
  428.  
  429.         function loginUser() {
  430.             let userData = {
  431.                 username: $('#formLogin input[name=username]').val(),
  432.                 password: $('#formLogin input[name=passwd]').val()
  433.             };
  434.             if (userData.username !== "" && userData.password !== "") {
  435.                 $.ajax({
  436.                     method: "POST",
  437.                     url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  438.                     headers: kinveyAppAuthHeaders,
  439.                     data: userData,
  440.                     success: loginSuccess,
  441.                     error: handleAjaxError
  442.                 });
  443.             } else {
  444.                 showError("Username AND Password should be filled")
  445.             }
  446.  
  447.             function loginSuccess(userInfo) {
  448.  
  449.                 saveAuthInSession(userInfo);
  450.                 showHideMenuLinks();
  451.                 listBooks();
  452.                 showInfo('login successful.');
  453.             }
  454.         }
  455.  
  456.         function showLoginView() {
  457.             showView("viewLogin");
  458.             $('#formLogin').trigger('reset');
  459.         }
  460.  
  461.         function showRegisterView() {
  462.  
  463.             $('#formRegister').trigger('reset');
  464.             showView('viewRegister');
  465.         }
  466.  
  467.         function getKinveyUserAuthHeaders() {
  468.             return {
  469.                 'Authorization': "Kinvey " +
  470.                 sessionStorage.getItem('authToken'),
  471.             };
  472.         }
  473.  
  474.         function listBooks() {
  475.             $('#books').empty();
  476.             showView('viewBooks');
  477.             $.ajax({
  478.                 method: "GET",
  479.                 url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books",
  480.                 headers: getKinveyUserAuthHeaders(),
  481.                 success: loadBooksSuccess,
  482.                 error: handleAjaxError
  483.             });
  484.  
  485.             function loadBooksSuccess(books) {
  486.  
  487.                 $('#books').empty();
  488.                 showInfo('Books loaded.');
  489.                 if (books.length == 0) {
  490.                     $('#books').text('No books in the library.');
  491.                 } else {
  492.                     let table = $(`
  493.                              <table>
  494.                                    <tr>
  495.                                       <th>Title</th>
  496.                                       <th>Author</th>
  497.                                       <th>Description</th>
  498.                                       <th>Price</th>
  499.                                       <th>Actions</th>
  500.                                    </tr>
  501.                              </table>`);
  502.                     for (let book of books) {
  503.                         let tr = $("<tr>");
  504.                         displayTableRow(tr, book);
  505.                         table.append(tr);
  506.                     }
  507.                     $('#books').append(table);//
  508.                 }
  509.             }
  510.  
  511.             function displayTableRow(tr, book) {
  512.  
  513.                 let links = [$("<a href='#'>more</a>")
  514.                         .click(function () {
  515.                             showMoreOfSelected(book)
  516.                         }), " "];
  517.                 if (book._acl.creator == sessionStorage.getItem("userId")) {
  518.  
  519.                     let deleteLink = $("<a href='#'>delete</a>")
  520.                             .click(function () {
  521.                                 let x;
  522.                                 if (confirm("are you sure you want to delete this?") == true) {
  523.                                     deleteBookById(book._id)
  524.                                 }
  525.  
  526.  
  527.                             });
  528.                     let editLink = $("<a href='#'>edit</a>")
  529.                             .click(function () {
  530.                                 loadBookForEdit(book._id)
  531.                             });
  532.                     links.push(deleteLink);
  533.                     links.push(" ");
  534.                     links.push(editLink);
  535.                 }
  536.  
  537.                 tr.append(
  538.                         $("<td>").text(book.book),
  539.                         $("<td>").text(book.author),
  540.                         $("<td>").text(book.description),
  541.                         $("<td>").text(book.price),
  542.                         $("<td>").append(links)
  543.                 )
  544.             }
  545.         }
  546.  
  547.         function showMoreOfSelected(book) {
  548.             $("#showSelected h3").text(book.book)
  549.             $("#textAuthor").val(book.author)
  550.             $("#textDescription").text(book.description)
  551.             showView('showSelected');
  552.  
  553.         }
  554.  
  555.         function deleteBookById(bookId) {
  556.             $.ajax({
  557.                 method: "DELETE",
  558.                 url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books/" + bookId,
  559.                 headers: getKinveyUserAuthHeaders(),
  560.                 success: deleteBooksSuccess,
  561.                 error: handleAjaxError
  562.             });
  563.             function deleteBooksSuccess() {
  564.                 showInfo("book deleted")
  565.                 listBooks();
  566.             }
  567.         }
  568.  
  569.         function showCreateBookView() {
  570.             $('#formCreateBook').trigger('reset');
  571.             showView('viewCreateBook');
  572.         }
  573.  
  574.         function logoutUser() {
  575.             sessionStorage.clear();
  576.             $('#loggedInUser').text("");
  577.             showHideMenuLinks();
  578.             showView('viewHome');
  579.             showInfo('Logout successful.');
  580.         }
  581.  
  582.         function registerUser() {
  583.             setTimeout(function(){ }, 3000);
  584.             let userData = {
  585.                 username: $('#formRegister input[name=username]').val(),
  586.                 password: $('#formRegister input[name=passwd]').val(),
  587.                 profilePicture:$('#formRegister input[name=image]').val()
  588.             };
  589.             if (userData.username !== "" && userData.password !== "") {
  590.  
  591.                 $.ajax({
  592.                     method: "POST",
  593.                     url: kinveyBaseUrl + "user/" + kinveyAppKey + "/",
  594.                     headers: kinveyAppAuthHeaders,
  595.                     data: userData,
  596.                     success: registerSuccess,
  597.                     error: handleAjaxError
  598.                 });
  599.             } else {
  600.                 showError("Username AND Password should be filled")
  601.             }
  602.  
  603.             function registerSuccess(userInfo) {
  604.  
  605.                 saveAuthInSession(userInfo);
  606.                 showHideMenuLinks();
  607.                 listBooks();
  608.                 showInfo('User registration successful.');
  609.             }
  610.         }
  611.  
  612.         function saveAuthInSession(userInfo) {
  613.             sessionStorage.setItem('authToken', userInfo._kmd.authtoken);
  614.             sessionStorage.setItem('userId', userInfo._id);
  615.  
  616.             let username = userInfo.username;
  617.             $('#loggedInUser')
  618.                     .text("Welcome, " + username + "!")
  619.                     .append( $("<img>").attr("src",userInfo.profilePicture))
  620.  
  621.  
  622.         }
  623.  
  624.         function handleAjaxError(response) {
  625.             let errorMsg = JSON.stringify(response);
  626.             if (response.readyState === 0)
  627.                 errorMsg = "Cannot connect due to network error.";
  628.             if (response.responseJSON &&
  629.                     response.responseJSON.description)
  630.                 errorMsg = response.responseJSON.description;
  631.             showError(errorMsg);
  632.         }
  633.  
  634.         function showInfo(message) {
  635.             $('#infoBox').text(message);
  636.             $('#infoBox').show();
  637.             setTimeout(function () {
  638.                 $('#infoBox').fadeOut();
  639.             }, 2000);
  640.         }
  641.  
  642.         function showError(errorMsg) {
  643.             $('#errorBox').text("Error: " + errorMsg);
  644.             $('#errorBox').show();
  645.         }
  646.  
  647.         function createBook() {
  648.             let bookData = {
  649.                 book: $('#viewCreateBook input[name=title]').val(),
  650.                 author: $('#viewCreateBook input[name=author]').val(),
  651.                 description: $('#viewCreateBook textarea[name=descr]').val(),
  652.                 price: $('#viewCreateBook input[name=price]').val()
  653.             };
  654.  
  655.  
  656.             if (bookData.book !== "" && bookData.author !== "" && bookData.description !== "" && bookData.price !== "") {
  657.  
  658.                 $.ajax({
  659.                     method: "POST",
  660.                     url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/books",
  661.                     headers: getKinveyUserAuthHeaders(),
  662.                     data: bookData,
  663.                     success: bookCreateSuccess,
  664.                     error: handleAjaxError
  665.                 });
  666.             } else {
  667.                 showError("Title,Author Description AND Price should be filled!")
  668.             }
  669.  
  670.             function bookCreateSuccess() {
  671.                 showHideMenuLinks();
  672.                 listBooks();
  673.                 showInfo('book added successfully.');
  674.             }
  675.         }
  676.  
  677.         function loadBookForEdit(bookId) {
  678.             $.ajax({
  679.                 method: "GET",
  680.                 url: kinveyBookUrl = kinveyBaseUrl + "appdata/" +
  681.                         kinveyAppKey + "/books/" + bookId,
  682.                 headers: getKinveyUserAuthHeaders(),
  683.                 success: loadBookForEditSuccess,
  684.                 error: handleAjaxError
  685.             });
  686.  
  687.             function loadBookForEditSuccess(book) {
  688.                 $('#formEditBook input[name=id]').val(book._id);
  689.                 $('#formEditBook input[name=title]').val(book.book);
  690.                 $('#formEditBook input[name=author]').val(book.author);
  691.                 $('#formEditBook input[name=price]').val(book.price);
  692.                 $('#formEditBook textarea[name=descr]').val(book.description);
  693.                 showView('viewEditBook');
  694.             }
  695.         }
  696.  
  697.         function editBook() {
  698.             let bookData = {
  699.                 book: $('#formEditBook input[name=title]').val(),
  700.                 author: $('#formEditBook input[name=author]').val(),
  701.                 price: $('#formEditBook input[name=price]').val(),
  702.                 description: $('#formEditBook textarea[name=descr]').val()
  703.             };
  704.             console.dir(bookData)
  705.             if (bookData.book !== "" && bookData.author !== "" && bookData.description !== "" && bookData.price !== "") {
  706.                 $.ajax({
  707.                     method: "PUT",
  708.                     url: kinveyBaseUrl + "appdata/" + kinveyAppKey +
  709.                     "/books/" + $('#formEditBook input[name=id]').val(),
  710.                     headers: getKinveyUserAuthHeaders(),
  711.                     data: bookData,
  712.                     success: editBookSuccess,
  713.                     error: handleAjaxError
  714.                 });
  715.  
  716.             } else {
  717.                 showError("Title,Author Description AND Price should be filled!")
  718.             }
  719.  
  720.                 function editBookSuccess(response) {
  721.                     alert("sux")
  722.                     listBooks();
  723.                     showInfo('Book edited.');
  724.                 }
  725.             }
  726.  
  727.         // Bind the navigation menu links
  728.         $("#linkHome").click(showHomeView);
  729.         $("#linkLogin").click(showLoginView);
  730.         $("#linkRegister").click(showRegisterView);
  731.         $("#linkListBooks").click(listBooks);
  732.         $("#linkCreateBook").click(showCreateBookView);
  733.         $("#linkLogout").click(logoutUser);
  734.         // Bind the form submit buttons
  735.         $("#buttonLoginUser").click(loginUser);
  736.         $("#buttonRegisterUser").click(registerUser);
  737.         $("#buttonCreateBook").click(createBook);
  738.         $("#buttonEditBook").click(editBook);
  739.         // Bind the info / error boxes: hide on click
  740.         $("#infoBox, #errorBox").click(function () {
  741.             $(this).fadeOut();
  742.         });
  743.         // Attach AJAX "loading" event listener
  744.         $(document).on({
  745.             ajaxStart: function () {
  746.                 $("#loadingBox").show()
  747.             },
  748.             ajaxStop: function () {
  749.                 $("#loadingBox").hide()
  750.             }
  751.         });
  752.         $("form").submit(function (e) {
  753.             e.preventDefault()
  754.         });
  755.     }
  756. </script>
  757. </body>
  758. </html>
  759. //////////////////////////////selfPreparation//////////////////////////////////
  760. <!DOCTYPE html>
  761. <html lang="en">
  762. <head>
  763.     <meta charset="UTF-8">
  764.     <title>Title</title>
  765.     <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  766. </head>
  767. <body onload="start()">
  768. <header id="header">
  769.     <a href="#" id="linkHome">Home</a>
  770.     <a href="#" id="linkLogin">Login</a>
  771.     <a href="#" id="linkRegister">Register</a>
  772.     <a href="#" id="linkAddClub">Add club</a>
  773.     <a href="#" id="linkDisplayClubs">Show Clubs</a>
  774.     <a href="#" id="linkLogout">logout</a>
  775.     <span id="welcome" style="float: right"></span>
  776. </header>
  777.  
  778.  
  779. <section id="sectionHome">
  780.     Tell us what's your favorite football team and why.
  781. </section>
  782.  
  783. <h1 id="infoDiv"></h1>
  784.  
  785. <main id="main">
  786.    <section id="sectionLogin">
  787.        <form id="viewLogin">
  788.            <div>Your name:<input type="text" class="in" id="nameLogin"></div>
  789.            <div>Password:<input type="password" class="in" id="passwordLogin"></div>
  790.            <button type="submit" id="btnLogin">Login</button>
  791.        </form>
  792.    </section>
  793.  
  794.    <section id="sectionRegister">
  795.        <form id="viewRegister">
  796.            <div>Your name:<input type="text" class="in" id="nameRegister"></div>
  797.            <div>Password:<input type="password" class="in" id="passwordRegister"></div>
  798.            <div>Confirm Password:<input type="password" class="in" id="confirmPasswordRegister"></div>
  799.            <button type="submit" id="btnRegister">Register</button>
  800.        </form>
  801.    </section>
  802.  
  803.    <section id="sectionAddClub">
  804.        <form id="viewAddClub">
  805.            <div>Club:<input type="text" class="in" id="addClub"></div>
  806.            <div>Country:<input type="text" class="in" id="addCountry"></div>
  807.            <div style="display: inline ;">Why You Support It?</div>
  808.            <textarea id="addDescription"></textarea>
  809.            <button type="submit" id="btnAddClub">Add</button>
  810.        </form>
  811.    </section>
  812.  
  813.    <section id="sectionEditClub">
  814.        <form id="viewEditClub">
  815.            <div>Club:<input type="text" class="in" id="editClub"></div>
  816.            <div>Country:<input type="text" class="in" id="editCountry"></div>
  817.            <div style="display: inline ;">Why You Support It?</div>
  818.            <textarea id="editDescription"></textarea>
  819.            <button type="submit" id="btnEditClub">Edit Changes</button>
  820.        </form>
  821.    </section>
  822.  
  823.    <section id="sectionShowClubs">
  824.        <form id="viewShowClubs">
  825.            <div id="teams">
  826.  
  827.            </div>
  828.        </form>
  829.    </section>
  830.  
  831.    <section id="sectionLogout">
  832.        <form id="viewLogout">
  833.  
  834.        </form>
  835.    </section>
  836. </main>
  837.  
  838. <footer>
  839.    No rights reserved.YOSIFOV 2016
  840. </footer>
  841.  
  842. <script>
  843.    function start() {
  844.        sessionStorage.clear(); // Clear user auth data
  845.        const kinveyBaseUrl = "https://baas.kinvey.com/";
  846.        const kinveyAppKey = "kid_HJOa7qYQe";
  847.        const kinveyAppSecret = "b5c713f9f48d4c18bb617636726127a0";
  848.        const kinveyAppAuthHeaders = {
  849.            'Authorization': "Basic " +
  850.            btoa(kinveyAppKey + ":" + kinveyAppSecret),
  851.        };
  852.        showHideHeaders();
  853.  
  854.        function showHideHeaders() {
  855.            clearAll();
  856.            if (sessionStorage.getItem("authToken")) {
  857.                $("#linkAddClub").show();
  858.                $("#linkDisplayClubs").show();
  859.                $("#linkLogout").show();
  860.                $("#linkRegister").hide();
  861.                $("#linkLogin").hide();
  862.            }
  863.            else {
  864.                $("#linkAddClub").hide();
  865.                $("#linkDisplayClubs").hide();
  866.                $("#linkLogout").hide();
  867.                $("#linkRegister").show();
  868.                $("#linkLogin").show();
  869.            }
  870.        }
  871.  
  872.        function clearAll() {
  873.            $("#sectionRegister").hide();
  874.            $("#sectionLogin").hide();
  875.            $("#sectionLogout").hide();
  876.            $("#sectionAddClub").hide();
  877.            $("#sectionShowClubs").hide();
  878.            $("#sectionEditClub").hide();
  879.        }
  880.  
  881.        function info(message) {
  882.            $("#sectionHome").append($("<h1>").text(message))
  883.            setTimeout(function () {
  884.                $("#sectionHome").find("h1").fadeOut();
  885.            }, 2000)
  886.        }
  887.  
  888.        function auth(userData) {
  889.            sessionStorage.setItem("authToken", userData._kmd.authtoken);
  890.            sessionStorage.setItem("userId", userData._id)
  891.        }
  892.  
  893.        //::::::KINVEY RELATED:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  894.  
  895.        function registerUser() {
  896.            let confirm = $("#confirmPasswordRegister").val()
  897.            let userData = {
  898.                username: $("#nameRegister").val(),
  899.                password: $("#passwordRegister").val()
  900.            }
  901.            if (userData.username == "" || userData.password == "" || confirm == "") {
  902.                info("All fields Should be Filled!");
  903.            }
  904.            else if (userData.password !== confirm) {
  905.                info("Password Don't Match")
  906.            }
  907.            else {
  908.                $.ajax({
  909.                    method: "POST",
  910.                    url: kinveyBaseUrl + "user/" + kinveyAppKey,
  911.                    headers: kinveyAppAuthHeaders,
  912.                    data: userData,
  913.                    success: successReg,
  914.                    error: errorHandler
  915.                })
  916.            }
  917.  
  918.            function successReg(userData) {
  919.                clearAll();
  920.                $("#confirmPasswordRegister").val('')
  921.                $("#nameRegister").val(''),
  922.                        $("#passwordRegister").val('')
  923.                $("#welcome").text("Welcome, " + userData.username + "!")
  924.                info("Registration Succesful");
  925.                auth(userData);
  926.                showHideHeaders();
  927.                viewDisplay();
  928.            }
  929.  
  930.        }
  931.  
  932.        function loginUser() {
  933.            let userData = {
  934.                username: $("#nameLogin").val(),
  935.                password: $("#passwordLogin").val()
  936.            }
  937.            if (userData.username == "" || userData.password == "") {
  938.                info("All fields Should be Filled!");
  939.            }
  940.            else {
  941.                $.ajax({
  942.                    method: "POST",
  943.                    url: kinveyBaseUrl + "user/" + kinveyAppKey + "/login",
  944.                    headers: kinveyAppAuthHeaders,
  945.                    data: userData,
  946.                    success: successLogin,
  947.                    error: errorHandler
  948.                })
  949.            }
  950.            function successLogin(userData) {
  951.                clearAll();
  952.                $("#welcome").text("Welcome, " + userData.username + "!")
  953.                info("Login Succesful");
  954.  
  955.                $("#nameLogin").val(""),
  956.                        $("#passwordLogin").val("")
  957.                auth(userData);
  958.                showHideHeaders();
  959.                viewDisplay();
  960.            }
  961.        }
  962.  
  963.        function addClub() {
  964.            let userData = {
  965.                team: $("#addClub").val(),
  966.                country: $("#addCountry").val(),
  967.                description: $("#addDescription").val()
  968.            }
  969.            if (userData.team == "" || userData.country == "" || userData.description == "") {
  970.                info("All fields Should be Filled!");
  971.            }
  972.            else {
  973.                $.ajax({
  974.                    method: "POST",
  975.                    url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/teams",
  976.                    headers: {
  977.                        "authorization": "Kinvey " + sessionStorage.getItem("authToken")
  978.                    },
  979.                    data: userData,
  980.                    success: successAdd,
  981.                    error: errorHandler
  982.                })
  983.            }
  984.  
  985.            function successAdd(userdata) {
  986.  
  987.                $("#addClub").val(""),
  988.                        $("#addCountry").val(""),
  989.                        $("#addDescription").val("")
  990.                info("Team Added");
  991.                clearAll();
  992.                viewDisplay();
  993.            }
  994.        }
  995.  
  996.        function errorHandler(error) {
  997.            info(error.responseJSON.error)
  998.        }
  999.  
  1000.        //::::::VIEWS::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  1001.  
  1002.        function viewLogin() {
  1003.            $("#sectionLogin").show()
  1004.        }
  1005.  
  1006.        function viewRegister() {
  1007.            $("#sectionRegister").show()
  1008.        }
  1009.  
  1010.        function viewAddClub() {
  1011.            $("#sectionAddClub").show();
  1012.        }
  1013.  
  1014.        function viewDisplay() {
  1015.            $.ajax({
  1016.                method: "GET",
  1017.                url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/teams",
  1018.                headers: {
  1019.                    "authorization": "Kinvey " + sessionStorage.getItem("authToken")
  1020.                },
  1021.  
  1022.                success: successDisplay,
  1023.                error: errorHandler
  1024.            })
  1025.  
  1026.            function successDisplay(userData) {
  1027.                $("#teams").empty();
  1028.                $("#teams")
  1029.                        .append(
  1030.                                $("<table>"),
  1031.                                $("<tr>"),
  1032.                                $("<th>").text("Club"),
  1033.                                $("<th>").text("Country"),
  1034.                                $("<th>").text("description")
  1035.                        )
  1036.                for (team of userData) {
  1037.                    let a = $("<tr>");
  1038.                    aa(a, team);
  1039.                    $("#teams").append(a);
  1040.                    function aa(a, team) {
  1041.                        a.append(
  1042.                                $("<tr>"),
  1043.                                $("<td>").text(team.team),
  1044.                                $("<td>").text(team.country),
  1045.                                $("<td>").text(team.description)
  1046.                        )
  1047.                        if (sessionStorage.getItem("userId") == team._acl.creator) {
  1048.                            a.append(
  1049.                                    $("<button>").text("delete").click(function () {
  1050.                                        let x;
  1051.                                        if (confirm("are you sure you want to delete this?") == true) {
  1052.                                            deleteTeam(team._id)
  1053.                                        }
  1054.  
  1055.  
  1056.                                    }), $("<button>").text("edit").click(function () {
  1057.                                        editTeam(team)
  1058.                                    })
  1059.                            )
  1060.                        }
  1061.                    }
  1062.                }
  1063.                $("#sectionShowClubs").show()
  1064.            }
  1065.        }
  1066.  
  1067.        function deleteTeam(teamId) {
  1068.            $.ajax({
  1069.                method: "DELETE",
  1070.                url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/teams/" + teamId,
  1071.                headers: {
  1072.                    "authorization": "Kinvey " + sessionStorage.getItem("authToken")
  1073.                },
  1074.                success: successDelete,
  1075.                error: errorHandler
  1076.            })
  1077.  
  1078.            function successDelete() {
  1079.                info("Team Deleted");
  1080.                clearAll();
  1081.                viewDisplay();
  1082.            }
  1083.        }
  1084.  
  1085.        function editTeam(team) {
  1086.            clearAll();
  1087.            $("#sectionEditClub").show();
  1088.            $("#editClub").val(team.team),
  1089.                    $("#editCountry").val(team.country),
  1090.                    $("#editDescription").val(team.description)
  1091.            $("#btnEditClub").click(function () {
  1092.                let userData = {
  1093.                    team: $("#editClub").val(),
  1094.                    country: $("#editCountry").val(),
  1095.                    description: $("#editDescription").val()
  1096.                }
  1097.                if (userData.team == "" || userData.country == "" || userData.description == "") {
  1098.                    info("All fields Should be Filled!");
  1099.                }
  1100.                else {
  1101.                    $.ajax({
  1102.                        method: "PUT",
  1103.                        url: kinveyBaseUrl + "appdata/" + kinveyAppKey + "/teams/" + team._id,
  1104.                        headers: {
  1105.                            "authorization": "Kinvey " + sessionStorage.getItem("authToken")
  1106.                        },
  1107.                        data: userData,
  1108.                        success: successEdit,
  1109.                        error: errorHandler
  1110.                    })
  1111.                }
  1112.            });
  1113.        }
  1114.  
  1115.        function successEdit() {
  1116.            info("Edit Successful!")
  1117.            clearAll();
  1118.            viewDisplay();
  1119.        }
  1120.  
  1121.        //::::::BUTTONS::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
  1122.  
  1123.        $("#linkHome").click(function () {
  1124.            clearAll();
  1125.  
  1126.        });
  1127.        $("#linkLogin").click(function () {
  1128.            clearAll();
  1129.            viewLogin();
  1130.        });
  1131.        $("#linkRegister").click(function () {
  1132.            clearAll();
  1133.            viewRegister()
  1134.        });
  1135.        $("#linkAddClub").click(function () {
  1136.            clearAll()
  1137.            viewAddClub();
  1138.        });
  1139.        $("#linkDisplayClubs").click(function () {
  1140.            clearAll();
  1141.            viewDisplay();
  1142.        });
  1143.        $("#linkLogout").click(function () {
  1144.            sessionStorage.clear()
  1145.            $("#welcome").text("")
  1146.            showHideHeaders();
  1147.  
  1148.            info("Logout Succesful");
  1149.        })
  1150.  
  1151.        $("#btnRegister").click(registerUser);
  1152.        $("#btnLogin").click(loginUser);
  1153.        $("#btnAddClub").click(addClub);
  1154.    }
  1155. </script>
  1156. </body>
  1157. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement