JavaScript /Typescript Common RESTFull CRUD Operation

Savindu Pasintha
2 min readOct 12, 2021

<script>
const url=’http://localhost:8081/myrestservice/service/person/';
function loadPerson() {
var id = document.getElementById(“txtId”).value
const options = {
method: “GET”,
headers: new Headers({‘Content-Type’: ‘application/json’, ‘Access-Control-Allow-Origin’: ‘*’}),
mode: ‘no-cors’
};

fetch(url + id, options)
.then(res => res.json())
.then(data => {
document.getElementById(‘txtName’).value = data.name;
document.getElementById(‘txtAge’).value = data.age;
});
}

function addPerson() {
(async () => {
const person = {
“id”: document.getElementById(‘txtId’).value,
“name”: document.getElementById(‘txtName’).value,
“age”: document.getElementById(‘txtAge’).value
};

const options = {
method: ‘POST’,
mode: ‘no-cors’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
‘Access-Control-Allow-Origin’: ‘*’
},
body: JSON.stringify(person)
};

const rawResponse = await fetch(url, options);
const content = await rawResponse.json();
})();
}

function updatePerson() {
(async () => {
const person = {
“id”: document.getElementById(‘txtId’).value,
“name”: document.getElementById(‘txtName’).value,
“age”: document.getElementById(‘txtAge’).value
};

const options = {
method: ‘PUT’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
‘Access-Control-Allow-Origin’: ‘*’
},
body: JSON.stringify(person)
};

const rawResponse = await fetch(url, options);
const content = await rawResponse.json();
})();
}

function deletePerson() {
(async () => {
var id= document.getElementById(“txtId”).value
const rawResponse = await fetch(url + id, {
method: ‘DELETE’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
‘Access-Control-Allow-Origin’: ‘*’
}
});
const content = await rawResponse.json();
})();
}

function clearPerson() {
document.getElementById(‘txtId’).value = “”
document.getElementById(‘txtName’).value = “”
document.getElementById(‘txtAge’).value = “”
}
</script>

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response