0

I am trying to create a Javascript, which is capturing user input and then sending it to my server. It's not working. Maybe someone knows why!

function capture() {
  fname = document.getElementsByName("firstname").value;
  lname = document.getElementsByName("lastname").value;
  address = document.getElementsByName("address").value;

}

function verify() {
  if (fname & lname & address != null) {
    data = [fname, lname, address];
    bdata = btoa(data);
    rbdata = bdata.replace("A", "B");
    jrbdata = JSON.stringify(rbdata);
  }
}

var url = "https://www.example.com/data";
var method = "POST";
var async = true;
var request = new XMLHttpRequest();

function send() {
  if (jrbdata != null) {
    request.open(method, url, async);
    request.setRequestHeader("Content-Type", "application/json");
    request.send(jrbdata);
  }
}

window.addEventListener("beforeunload", send());

I should receive the POST with php:

<?php
 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Allow-Methods: POST,GET");
 header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content- 
 Type, Accept");
 print_r($_POST); ?>
9
  • Could you post your HTML, please? Commented Dec 29, 2019 at 16:41
  • jrbdata is not available to send unless you call verify first Commented Dec 29, 2019 at 16:41
  • 2
    This addEventListener("beforeunload", send()) should be addEventListener("beforeunload", send). Adding () after function name will call the function and return value (undefined) will be assigned as handler Commented Dec 29, 2019 at 16:42
  • 2
    Also, your capture function is broken. Standard thing that happens to people that have been doing jQuery for a long time. stackoverflow.com/questions/10693845/… Commented Dec 29, 2019 at 16:46
  • 1
    Also you likely want to make var async = false; if you need this to happen before the browser leaves your page Commented Dec 29, 2019 at 16:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.