Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- let username = 'guest';
- let password = 'g';
- let base64encode = btoa(username + ':' + password);
- let authorization = {"Authorization": "Basic " + base64encode};
- let countriesInDataBase = [];
- loadData();
- $('#addBtn').on('click', addCountry);
- $('#deleteBtn').on('click', deleteCountry);
- function addCountry() {
- let name = $('#countryInput').val();
- if (name.length > 0 && !countriesInDataBase.includes(name)) {
- let jsonData = JSON.stringify({name: name});
- countriesInDataBase.push(name);
- $.ajax({
- method: 'POST',
- url: `https://baas.kinvey.com/appdata/kid_HJxYjhw9z/countries`,
- headers: authorization,
- data: jsonData,
- contentType: 'application/json'
- }).then(appendCountry).catch(handleError);
- function appendCountry() {
- $('#countries').append($(`<option>${name}</option>`));
- $('#func').text(`${name} added!`).fadeIn(300).fadeOut(2000);
- }
- } else {
- $('#func').text(`Invalid country!`).fadeIn(300).fadeOut(2000);
- }
- $('#countryInput').val('');
- }
- function deleteCountry() {
- let selected = $('#countries').find(':selected').val();
- let idToDelete;
- $.ajax({
- method: 'GET',
- url: `https://baas.kinvey.com/appdata/kid_HJxYjhw9z/countries`,
- headers: authorization
- }).then(findAndDeleteCountry).catch(handleError);
- function findAndDeleteCountry(res) {
- for(let country of res){
- if(country.name = selected){
- idToDelete = country._id;
- break;
- }
- }
- $.ajax({
- method: 'DELETE',
- url: `https://baas.kinvey.com/appdata/kid_HJxYjhw9z/countries/${idToDelete}`,
- headers: authorization,
- contentType: "application/json",
- }).then().catch(handleError)
- }
- }
- function loadData() {
- $.ajax({
- method: 'GET',
- url: `https://baas.kinvey.com/appdata/kid_HJxYjhw9z/countries`,
- headers: authorization
- }).then(addCountries).catch(handleError);
- function addCountries(res) {
- for (let country of res) {
- $('#countries').append($(`<option>${country.name}</option>`));
- countriesInDataBase.push(country.name);
- }
- }
- }
- function handleError(err) {
- console.log('Error: ' + err.status + " " + err.statusText)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement