简体   繁体   English

使用JavaScript PHP jQuery将网页中的数据发布到Google表格

[英]Posting data from webpage using JavaScript PHP jQuery to Google Sheet

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. 我遵循了这个答案( PHP的jQuery Ajax POST示例 ),但是我试图将数据发送到Google表格。 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. 我已经在Google表格上使用了该代码,因为可以通过直接从该表格运行代码来向其中添加数据。

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). 下面的代码是一个浮动页脚,包含在整个网页的代码中(其中jquery-1.11.0.min.js和jquery-migrate-1.2.1.min.js已被调用)。 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 ). 当我单击“提交”按钮时,页面看起来像是在处理请求,但是Google表格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. 与本网站上的大多数网站相比,我在Web开发方面经验不足。 So I'm sure it's something simple I am missing! 因此,我确定这是我所缺少的简单东西!

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! 我不完全理解为什么它起作用,但是取出脚本并将其放在页面的顶部,HTML似乎起作用了! 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! 可能是因为脚本在元素之后出现是一个问题,或者是在页面主要HTML内的HTML内包含$(document).ready()引起的,或者是其他原因! 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. 在页面HTML开头的代码顶部(但在声明jQuery.js文件之后),我放置了已经看到的脚本,但是做了一些外观上的更改。 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: 我还将显示脚本之前包含的两个jQuery文件:

<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: 在HTML主体的最下方是这段代码,用于放置我的页脚:

    #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! 非常感谢杰伊·布兰查德Jay Blanchard)向我提出疑问,我的脚本是否甚至已经触发,这激发了我将脚本拉出并放到其他地方的念头! 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! 但我希望这对其他人有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM