0

Before you say this is a duplicate, hear me out. I followed this answer (jQuery Ajax POST example with PHP), but I am trying to send the data to a Google Sheet. I have already got the code working on the Google Sheet, as I can add data to it by running my code directly from the sheet.

However, getting it to work with my webpage is apparently the problem. Even though I have followed the answer to the question I posted above, I think there is something more at play here that has to do with my lack of experience working in this area.

The code below is to a floating footer and is contained within the code of the whole webpage (where jquery-1.11.0.min.js and jquery-migrate-1.2.1.min.js have already been called). When I click on the submit button, the page looks like it processes the request, but nothing ever appears on the Google Sheet, Sheet1 (https://docs.google.com/spreadsheets/d/19l2kSHdBKEWtIFX44FxLBdvCoKjy7VqPF4IW6C1xAZc/edit?usp=sharing).

#document
<html>
<body>
<div class="floater-footer" id="the-floater-footer">
<span id="myTestSpan"></span>
  <div class="row">
    <div class="col-md-1 col-sm-2 col-xs-3"><p>Newsletter</p></div>
    <div class="col-md-8 col-sm-7 col-xs-9">

      <form id="floater_footer" class="validate subscribe_form">
          <div id="subscrive_group wow fadeInUp">

          <!-- <input type="email" value="" name="EMAIL" class="form-control subscribe_mail" id="mce-EMAIL" placeholder="email address" required /> -->
          <input type="text" class="form-control subscribe_mail" id="bar" name="bar" value="" placeholder="email address" required />
          <!-- <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="subscr_btn subscribe_btn"> -->
          <input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />

          </div>
      </form>
    </div>
    <div class="col-md-3 col-sm-3 hidden-xs">
      <div class="pull-right">
        <!-- social media icons here -->
       </div>
    </div>
  </div>
</div>

<script type="text/javascipt">

jQuery( document ).ready(function( $ ) {
// variable to hold request
var request;
// bind to the submit event of our form
$("#floater_footer").submit(function(event){
    // abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);
    // let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");
    // serialize the data in the form
    var serializedData = $form.serialize();

    // let's disable the inputs for the duration of the ajax request
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);
    //$('#result').text('Sending data...');

    // fire off the request to /form.php
    request = $.ajax({
        url: "https://script.google.com/macros/s/AKfycbyQIDmSInumcrNmU4zxIa4pV8tIlN3A9zx5L5o1hH4qNdP9nDw/exec",
        type: "post",
        data: serializedData
    });

    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console
        //$('#result').html('<a href="https://docs.google.com/spreadsheets/d/10tt64TiALYhPMqR2fh9JzkuhxW7oC0rXXPb_pmJ7HAY/edit?usp=sharing" target="_blank">Success - see Google Sheet</a>');
        console.log("Hooray, it worked!");
    });

    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });

    // callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // reenable the inputs
        $inputs.prop("disabled", false);
    });

    // prevent default posting of form
    event.preventDefault();
});
});

</script>

</body>
</html>

Any suggestions on what could be going wrong? I am quite inexperienced when it comes to web development, as compared to most on this site. So I'm sure it's something simple I am missing!

Community
  • 1
  • 1
Nimex
  • 33
  • 4
  • Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there an errors reported? Are you running this on a web-server? – Jay Blanchard Apr 19 '16 at 18:07
  • I have not watched for that in the developer tools. I don't know how to do that, as the elements, console, and network tabs in Chrome are the only ones I use. I included jquery-1.11.0.min.js and jquery-migrate-1.2.1.min.js. The only errors reported are unrelated to this problem, and they aren't really errors that I'm concerned with right now. It is actually running on a live site. There isn't much traffic on it, so I'm testing with it directly. – Nimex Apr 19 '16 at 18:21
  • Those are a part of the developer tools. – Jay Blanchard Apr 19 '16 at 18:22
  • Right, but I'm saying I don't know where I would see the request/response there. – Nimex Apr 19 '16 at 18:23
  • It would be in the network tab. – Jay Blanchard Apr 19 '16 at 18:23
  • The only thing I see that isn't normal page data is `?bar=testtext`. I used `bar` as the name for the text field I'm trying to send. It's appearing in the URL for some reason, though, it shouldn't. Perhaps what is actually happening is that the form isn't being submitted properly. It may just be reloading the page with the form data serialized and showing in the URL, but never doing the AJAX request. Does that makes sense? – Nimex Apr 19 '16 at 18:30
  • 1
    If it makes the AJAX request you're losing that when the page reloads. If it is reloading the page you are having a problem with `event.preventDefault();` – Jay Blanchard Apr 19 '16 at 18:34
  • I don't know why it worked, but I left the footer encapsulated in HTML as shown, but moved the script out to the head of the main page HTML. You gave me the idea that my script wasn't triggering at all with your last comment :) Do you want to make that an answer that I can then mark correct to give you rep, or should I do it? Thanks for all the help! – Nimex Apr 20 '16 at 01:56
  • 1
    You can do it , glad you got it solved. – Jay Blanchard Apr 20 '16 at 02:48

1 Answers1

0

I don't completely understand why it worked, but taking out the script and putting it in the head of the page HTML seemed to work! Perhaps this was because having the script come after the elements was an issue, or perhaps having a $(document).ready() inside of an HTML that was inside the page's main HTML caused issue, or perhaps it was something else! No matter which one it is, the following solved the problem.

Up at the top of the code in the head of the page's HTML (but after the jQuery.js files were declared), I placed the script you saw already, but with some cosmetic changes. I'll put it here in the event I did indeed change something important that I didn't realize. I will also show the two jQuery files I included before the script:

<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>


<script type="text/javascript">
//this is for writing the newsletter signup out to a spreadsheet for the floating footer

$( document ).ready(function( $ ) {
// variable to hold request
var request;
// bind to the submit event of our form
$("#floater_footer").submit(function(event){
    // abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);
    // let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");
    // serialize the data in the form
    var serializedData = $form.serialize();

    // let's disable the inputs for the duration of the ajax request
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);
    //$('#result').text('Sending data...');


    if( $('#email1').val() == "Email Received!" ) {

        //do nothing
        //basically, they pressed the button again on accident

    } else {

        // fire off the request to the Google Sheet script
        request = $.ajax({
            url: "https://script.google.com/macros/s/AKfycbyQIDmSInumcrNmU4zxIa4pV8tIlN3A9zx5L5o1hH4qNdP9nDw/exec",
            type: "post",
            data: serializedData
        });

    }


    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console
        //$('#result').html('<a href="https://docs.google.com/spreadsheets/d/10tt64TiALYhPMqR2fh9JzkuhxW7oC0rXXPb_pmJ7HAY/edit?usp=sharing" target="_blank">Success - see Google Sheet</a>');
        $('#email1').val('Email Received!');
        console.log("Newsletter signup complete!");
    });

    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });

    // callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // reenable the inputs
        $inputs.prop("disabled", false);
    });

    // prevent default posting of form
    event.preventDefault();
});
});

</script>

Further down into the body of the HTML was this code where my footer was to be placed:

    #document
<html>
<body>
<div class="floater-footer" id="the-floater-footer">
<span id="myTestSpan"></span>
  <div class="row">
    <div class="col-md-1 col-sm-2 col-xs-3"><p>Newsletter</p></div>
    <div class="col-md-8 col-sm-7 col-xs-9">

      <form id="floater_footer" class="validate subscribe_form">
          <div id="subscrive_group wow fadeInUp">

          <input type="text" class="form-control subscribe_mail" id="email1" name="emailSignup" value="" placeholder="email address" required />

          <input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />

          </div>
      </form>
    </div>
    <div class="col-md-3 col-sm-3 hidden-xs">
      <div class="pull-right">
        <!-- bunch of social media links/icons -->
       </div>
    </div>
  </div>
</div>
</body>
</html>

Hopefully that will help somebody that has this problem in the future. You may see a reason this worked that I do not.

Big thanks to Jay Blanchard for making me question if my script was even triggering at all, which inspired me to pull the script out and put it somewhere else! The script almost certainly wasn't firing at all, and was the root of the problem. But WHY that was, I don't know. But I hope this helps someone else!

Community
  • 1
  • 1
Nimex
  • 33
  • 4