问题
I am trying to submit a form to Google Sheets. This step is successful and I am getting all the numbers in the sheet. Now I want to display a success message after the form is submitted and the result from Google Sheets is ok. How do I do it?
I have tried various messages in javascript and ajax, but don't have much understanding about it. I have shown my code below so you can have a look at it.
<form name="submit-to-google-sheet">
<select class="form-control custom-form" name="country_code" id="country_code">
<option name="country_code" value="+91">India 91</option>
<option name="country_code" value="+93">Afghanistan 93</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group spec-col col-md-8 col-lg-8 col-sm-12">
<input type="text" class="form-control custom-form" id="phone_no" name="phone_no" placeholder="Enter the Number">
</div>
</div>
<button class="btn btn-submit" id="submit" type="submit">Submit</button>
</div>
</form>
For Submitting the content to Google Sheets, here is the code
<script>
const scriptURL = 'GOOGLE SHEETS URL'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
})
</script>
After the form is successful, I can see a success message in the console. Instead, I want to show a simple one-word line in HTML, that thanks a lot. Your submission is successful, once the response from Google Sheets is Ok and hide the form.
Edit: The rest of the code can be referenced from here: https://github.com/jamiewilson/form-to-google-sheets
回答1:
Bellow the button create a blank response message
tag just like this
<button class="btn btn-submit" id="submit" type="submit">Submit</button>
<p id="response_message"></p>
Now in the scripts make the following change in the fetch function:
form.addEventListener('submit', e => {
e.preventDefault()
var response_message = document.getElementById("response_message");
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => response_message.innerHTML = "Success!")
.catch(error => response_message.innerHTML = "Error!")
})
回答2:
If you are using a Google Form to submit the data to the Google Sheet there is a setting in the Forms settings where you can display a response on submit. No code needed.
来源:https://stackoverflow.com/questions/56831426/submit-form-should-display-message-after-successful-submit-to-google-sheets