The following example demonstrates how to Add a product (or anything) to a Database Table asynchronously, using AJAX, and TypeScript.
declare var document;
declare var xhr: XMLHttpRequest;
window.onLoad = () =>
{
Start();
};
function Start()
{
// Setup XMLHttpRequest (xhr).
if(XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
AttachEventListener(document.body, "click", HandleCheckBoxStateChange);
}
function AttachEventListener(element: any, e, f)
{
// W3C Event Model.
if(element.addEventListener)
{
element.addEventListener(e, f, false);
}
else if(element.attachEvent)
{
element.attachEvent("on" + e, (function(element, f)
{
return function()
{
f.call(element, window.event);
};
})
(element, f));
}
element = null;
}
function HandleCheckBoxStateChange(e)
{
var element = e.target || e.srcElement;
if(element && element.type == "checkbox")
{
if(element.checked)
{
AddProductToCart(element);
}
else
{
// It is un-checked.
// Remove item from cart.
}
}
else
{
break;
}
}
AddProductToCart(e)
{
var element = <HTMLInputElement>document.getElementById(e.id);
// Add the product to the Cart (Database table)
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
if(element != null)
{
console.log("200: OK");
}
else
{
console.log(":-(");
}
}
else
{
// The server responded with a different response code; handle accordingly.
// Probably not the most informative output.
console.log(":-(");
}
}
}
var parameters = "ProductID=" + encodeURIComponent(e.id) + "&" + "Action=Add&Quantity=" + element.value;
xhr.open("POST", "../Cart.cshtml");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", parameters.length.toString());
xhr.setRequestHeader("Connection", "close");
xhr.send(parameters);
return e.id;
}
In order to make this example complete, update your server-side code to actually insert this data into the database. The code above assumes you are using C# and have a Cart.cshtml
file. However, simply replace cshtml
with php
, and write your own server-side logic using the language of your choice.