Solution
function myfunction() {
var firstname = document.getElementById("fname").value;
var lastname = document.getElementById("lname").value;
var dict_values = {firstname, lastname} //Pass the javascript variables to a dictionary.
console.log(dict_values); // Prints the variables to console window, which are in the JSON format
$.ajax({
url:"/test",
type:"POST",
dataType : "json",
contentType : "application/json; charset=utf-8",
data: JSON.stringify(dict_values)});
}