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); ?>
  • Could you post your HTML, please? –  Dec 29 '19 at 16:41
  • `jrbdata` is not available to send unless you call verify first – mplungjan Dec 29 '19 at 16:41
  • Is this all of your JS? –  Dec 29 '19 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 – Rajesh Dec 29 '19 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. https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return?noredirect=1 – connexo Dec 29 '19 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 – mplungjan Dec 29 '19 at 16:49
  • The right way for using operator 'and' is `&&` `if(fname && lname && address) { }` – Addis Dec 29 '19 at 16:51
  • Thanks for the comments. @Rajesh this helped, but capture function is still not working. When there should be a xhr request, there is none. I validated in Chrome Developer Network XHR Tab. – vexejo9905 Dec 29 '19 at 17:13
  • @vexejo9905 You have recorded `beforeUnload` event. First try it on a button click. This way you are sure your code is working. Then try to integrate with close event – Rajesh Dec 30 '19 at 05:50

0 Answers0