I'm trying to make a post request to a node.js Server to submit some data to the server using Fetch API. Now I want to display a success message according to the response sent back by the server, but I'm unable to do so as the page refreshes itself every time I try to do so. I've tried many different ways to stop this (eg. e.preventDefault(), changing button to div, changing the type of button to button instead of submit) but nothing seems to work. Please someone help me out. Posting both my HTML as well as Javascript code here. Also I'm very new to web development (experience of 2 months only), so please can you also tell me is the method I'm following is right or wrong. Thanks!
I'm using Semantic UI for the css part
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
<link rel="stylesheet" href="./styles/styles.css">
</head>
<body>
<div class="ui fixed inverted menu">
<div class="ui container">
<a href="#" class="header item">
My Project
</a>
</div>
</div>
<div class="ui main text container">
<form class="ui loading form" id="main_form">
<div class="field">
<textarea name="message" id="otp_message" cols="30" rows="10"></textarea>
</div>
<div class="ui success message">
<div class="header">OTP Sent</div>
<p>You've successfully sent the OTP on Mobile Number</p>
</div>
<div class="ui center aligned grid container">
<div class="ui row">
<button type="submit" class="ui green button" id="btn_validate">Send</button>
</div>
</div>
</form>
</div>
</body>
<!-- <script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script> -->
<script src="./scripts/send_message.js"></script>
</html>
Javascript:
let id;
let otp;
function processUser() {
const parameters = location.search.substring(1);
id = (parameters.split("=")[1]);
let url = 'http://localhost:3030/ShowContacts?id=';
url += id;
let data;
fetch(url, {method:"GET"})
.then(response => {
if (response.status === 404) throw new Error('User not found');
return response.text();
})
.then(response => {
data = JSON.parse(response);
// document.getElementById('name').innerText += ' ' + jsonDATA.first_name + ' ' + jsonDATA.last_name;
// document.getElementById('phone_number').innerText += ' ' + jsonDATA.mobile_number;
generateOTP();
})
.catch(e => {
console.log(e.message);
});
}
processUser();
async function generateOTP() {
let url = 'http://localhost:3030/getOTP';
fetch(url, { method: "GET" })
.then(response => {
if (response.status === 404) throw new Error('Unable to generate otp');
return response.text();
})
.then(response => {
const jsonDATA = JSON.parse(response);
otp = jsonDATA.otp;
document.getElementById('main_form').classList.remove('loading');
document.getElementById('otp_message').value = `Hi. Your OTP is: ${otp} . Please do not share it with anybody else.`;
})
.catch(e => {
console.log(e.message);
})
}
const myForm = document.getElementById('main_form');
// const btn = document.getElementById('btn_validate');
document.forms['main_form'].addEventListener('submit', (event) => {
event.preventDefault();
let otpSent = false;
const message = document.getElementById('otp_message').value;
const raw = JSON.stringify({
id: id,
message: message,
otp: otp
});
const requestOptions = {
method: 'POST',
body: raw
};
const url = "http://localhost:3030/otpSent";
fetch(url, requestOptions)
.then(response => response.json())
.then(response => {
otpSent = response.success;
if (otpSent) {
let prevClassValue = myForm.getAttribute('class');
prevClassValue += " success";
myForm.setAttribute('class', prevClassValue);
}
})
.catch(error => console.log(error));
})
return false
at the end of the event handling function. – Thevs Mar 7 '20 at 17:35