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); ?>
jrbdatais not available to send unless you call verify firstaddEventListener("beforeunload", send())should beaddEventListener("beforeunload", send). Adding()after function name will call the function and return value (undefined) will be assigned as handlercapturefunction is broken. Standard thing that happens to people that have been doing jQuery for a long time. stackoverflow.com/questions/10693845/…