function ajaxPost (form, token, callback) { var url = form.action, xhr = new XMLHttpRequest(); //This is a bit tricky, [].fn.call(form.elements, ...) allows us to call .fn //on the form's elements, even though it's not an array. Effectively //Filtering all of the fields on the form var params = [].filter.call(form.elements, function(el) { return true; }) .map(function(el) { //Map each field into a name=value string, make sure to properly escape! return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value); }).join('&'); //Then join all the strings by & xhr.open("POST", url); // Changed from application/x-form-urlencoded to application/x-form-urlencoded xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //.bind ensures that this inside of the function is the XHR object. xhr.onload = callback.bind(xhr); //params += '&g-recaptcha-response=' + token; //All preperations are clear, send the request! xhr.send(params); } function onCallSub(token) { document.getElementById("postformSenderUrl").value = window.location.href; ajaxPost(document.forms['pform'], token, function() { document.getElementById('csepostform').innerHTML = 'Kiitos! Olemme pian yhteyksissä.'; }); } var html = ''; html += '
'; document.getElementById('csepostform').innerHTML = html; var script = document.createElement('script'); script.src = 'https://www.google.com/recaptcha/api.js'; document.head.appendChild(script);