|
| 1 | +/**Calling Data From API Using Fetch Object */ |
| 2 | +function AjaxCall() { |
| 3 | + let url = 'https://jsonplaceholder.typicode.com/users' |
| 4 | + fetch(url, { method: 'GET' }) |
| 5 | + .then((response) => { |
| 6 | + return response.json() |
| 7 | + }) |
| 8 | + .then((resJson) => { |
| 9 | + let user = document.getElementById('users') |
| 10 | + let primBtn = document.getElementById('primInput') |
| 11 | + primBtn.setAttribute('disabled', '') |
| 12 | + |
| 13 | + for (let i = 0; i < resJson.length; i++) { |
| 14 | + user.innerHTML += `<option value="${resJson[i].name}">${resJson[i].name}</option>` |
| 15 | + } |
| 16 | + |
| 17 | + let show = document.getElementById('show') |
| 18 | + let domData = document.getElementById('data') |
| 19 | + show.removeAttribute('disabled','') |
| 20 | + |
| 21 | + show.onclick = () => { |
| 22 | + domData.innerHTML = `User ID Is : ${resJson[user.selectedIndex].id} |
| 23 | + & Email is : ${resJson[user.selectedIndex].email} |
| 24 | + & Phone Number Is :${resJson[user.selectedIndex].phone} ` |
| 25 | + } |
| 26 | + }) |
| 27 | + .catch(err => err) |
| 28 | +} |
| 29 | +/** Sending Data Using HttpReq Method 'POST' */ |
| 30 | +function AjaxPost() { |
| 31 | + let url = 'https://jsonplaceholder.typicode.com/posts' |
| 32 | + let bodyy = { |
| 33 | + title: prompt('Enter Your Name'), |
| 34 | + body: prompt('Enter Color'), |
| 35 | + userId: 2 |
| 36 | + } |
| 37 | + fetch(url, { |
| 38 | + method: 'POST', |
| 39 | + body: JSON.stringify(bodyy), |
| 40 | + headers:{'content-type' : 'application/json'}}) |
| 41 | + .then((response) => { |
| 42 | + return response.json() |
| 43 | + }) |
| 44 | + .then((res) => { |
| 45 | + let msg = document.getElementById('suc') |
| 46 | + msg.innerHTML = `Information Added Successfully!<br> |
| 47 | + Name : ${res.title}<br> |
| 48 | + Color : ${res.body}<br> |
| 49 | + ID : ${res.userId}<br> |
| 50 | + ` |
| 51 | + console.log(res) |
| 52 | + }) |
| 53 | + |
| 54 | + |
| 55 | +} |
0 commit comments