You can achieve this with pure JS by using xmlhttp.
This one omits the wrapping of the data
variable, so you get first_name
and last_name
as their own parameters.
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
params = "first_name=" + first_name + "&last_name=" + last_name;
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
You can also send the data as JSON like this:
function addUser(first_name, last_name){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("successfully added user");
console.log(xmlhttp.response);//this is the response from the server
}
}
xmlhttp.open("POST", "http://testserver.com/add_user",true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//Not sure if you need the Content-length here or not.
xmlhttp.send(JSON.stringify({"data"=>{"first_name"=>first_name, "last_name" => last_name}}));
}
I find this approach cleaner than using an invisible form when it isn't really needed.