我想在重力表单提交后控制台记录整个表单数据

问题描述 投票:0回答:1

我正在尝试使用此代码,但这不起作用

jQuery(document).ready(function() {
    jQuery(document).on('gform_confirmation_loaded', function(event, form_id) {
        if (form_id === 3) { // Replace 3 with your actual form ID
            var formData = jQuery('#gform_3').serializeArray(); // Replace 3 with your actual form ID

            // Log the full form data
            console.log('Full Form Data:', formData);
        }
    });
});
wordpress gravity-forms-plugin gravityforms
1个回答
0
投票

@Caleb 是对的,此事件仅适用于 ajax 表单。当此事件触发时,您提交的数据已全部消失。

但是..您可能会偷偷摸摸地将提交数据保存到本地存储,这适用于任何一种情况..ajax或非ajax gforms:-)

确保将这一切添加到 jQuery 文档就绪函数中...

// first listen for your form submission
$('#gform_3').on('submit', function(e) {

  // temporally prevent form from submitting on submit
  e.preventDefault();

  // lets get the form data as serialised array
  let formData = $(this).serializeArray();

  // set an empty form object (so we can log as an 1 object later)
  let formObj = {};

  // loop thru our form data and add them to our form object
  $.each(formData, function(i, field) {

    // add by key name and field value to object
    formObj[field.name] = field.value;

  });

  // now lets be sneaky and save to local storage temporally 
  localStorage.setItem('formData', JSON.stringify(formObj));

  // now let finish what we started and submit the form!
  this.submit();

});

好的,这就是在提交之前将表单数据保存到本地存储,然后在保存表单数据后提交。

因此,紧接着在同一个 jQuery 文档就绪函数中添加下面的内容,这将在页面加载时获取我们的本地存储表单数据...

// get our saved form data
let savedFormData = localStorage.getItem('formData');

// if we got form data
if(savedFormData) {

  // parse the saved form data back to object
  let formDataObj = JSON.parse(savedFormData);

  // then lets console log this form submission...
  console.log(formDataObj);

  // then lets remove the local storage form data but not really needed as this will override everytime, but removing keeps tidy I guess.
  localStorage.removeItem('formData');

}

好的,如果您的重力表单是 ajax 加载到您的页面上,您可以使用它作为加载确认事件的后备,只需在上面的代码后面包含它

// fallback gform confirmation event to still log the message if the page does not refresh
jQuery(document).on('gform_confirmation_loaded', function(event, form_id) {

  // taken from you code to only hit form id 3
  if (form_id === 3) { // Replace 3 with your actual form ID

    // get our saved form data
    let savedFormData = localStorage.getItem('formData');

    // if we got form data
    if(savedFormData) {

      // parse the saved form data back to object
      let formDataObj = JSON.parse(savedFormData);

      // then lets console log this form submission...
      console.log(formDataObj);

      // then lets remove the local storage form data but not really needed as this will override everytime, but removing keeps tidy I guess.
      localStorage.removeItem('formData');

    }

  }

});

这尚未经过测试,但我确信这将使您走上正确的道路,在正常模式或ajax模式下安慰重力表单id的表单提交。

祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.