简体   繁体   中英

A piece of javascript in footer.php wordpress does work on PC but not on mobile

I have the following code in my footer.php on my wordpress website

var myForm = document.getElementById("questionnaire");
if (myForm) {
  myForm.onsubmit = function() {
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/xxxxx/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onload = function() {
  if(xhr.readyState == 4 && xhr.status == 200) {
    var response = JSON.parse(xhr.responseText);
    var result = response.result;
    for (var i in result) {
      var e = result[i];
      if (e) {
        var li = document.createElement('li');
        if (e.url) {
          var a = document.createElement('a');
          a.href = e.url;
          a.textContent = e.name;
          li.appendChild(a);
        } else {
          li.textContent = e.name;
        }
        resultList.appendChild(li);
      }
    }
    busyDiv.hidden = true;
    resultDiv.hidden = false;
  }
}

var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','xxx','yyyy'];
var params = [];
for (var i in fields) {
  var field = fields[i];
  params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));

questionDiv.hidden=true;
busyDiv.hidden=false;


return false;
  };
}
</script>

This has allowed me to write and quote data from a google sheet

Now all this works on PC but it delivers 404 not found error on mobile site and the website itself is preset to be mobile responsive.

Can somebody help please?

Jane

What does your form html look like? I suspect that your mobile browser is trying to submit the form via the standard - non AJAX way and therefore is directing the browser to the url in the "action" attribute of your form. Try the following to stop this default behaviour

var myForm = document.getElementById("questionnaire");
if (myForm) {
  myForm.onsubmit = function(evt) {
    evt.preventDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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