Reputation: 481
I'm using AJAX and a google spreadsheet to collect email data for a newsletter by taking the POST data from a form field and sending it to the spreadsheet through google forms. I can't get the code to stop the page from redirecting to google's thank you page. This is the AJAX and form code below.
<form class="form-inline" role="form" action="https://docs.google.com/forms/d/1TEPXPqigGuN8sayYjz-sk6H-5wAbPaImsgadM2PBFAk/formResponse" method="POST" id="newsletter-form" target="_self" onsubmit="">
<input type="text" name="entry_291075079" value="" class="form-control" id="Email" dir="auto" placeholder="[email protected]">
</form>
<script>
$("#newsletter-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/1TEPXPqigGuN8sayYjz-sk6H-5wAbPaImsgadM2PBFAk/formResponse",
data: $(this).serialize(),
type: "POST",
dataType: "xml",
success: function(data) {
console.log('Submission successful');
},
error: function(xhr, status, error) {
console.log('Submission failed: ' + error);
}
});
});
</script>
Upvotes: 1
Views: 3041
Reputation: 337656
Your page is being redirected because it is doing a standard form submission via POST - your javascript code is not attached to the form submission at all. To do what you require you could attach the JS code to the submit
event of the form, and stop the submission by using preventDefault()
, something like this:
<script>
$('#ss-form').submit(function(e) {
e.preventDefault();
$.ajax({
url: "url to google form responses",
data: $(this).serialize(),
type: "POST",
dataType: "xml",
success: function(data) {
console.log('Submission successful');
},
error: function(xhr, status, error) {
console.log('Submission failed: ' + error);
}
});
});
</script>
Upvotes: 1