Skip to content

Instantly share code, notes, and snippets.

@dharmavir
Created April 22, 2011 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharmavir/936328 to your computer and use it in GitHub Desktop.
Save dharmavir/936328 to your computer and use it in GitHub Desktop.
Simple Plain AJAX Helper function - without any Javascript library
<html>
<head>
<title>Raw AJAX Example Demo</title>
</head>
<body>
Val 1:&nbsp;<input type="text" id="val1" name="val1" value="" />
&nbsp;+&nbsp;
Val 2:&nbsp;<input type="text" id="val2" name="val2" value="" />
&nbsp;
<input type="button" value="=" onclick="doSum()"/>
&nbsp;
<input type="text" id="sum" name="sum" value="" />
<script type="text/javascript" src="plain_ajax.js"></script>
<script type="text/javascript">
var displaySum = function()
{
if (this.readyState == 4)
{
document.getElementById("sum").value = this.responseText;
}
}
displaySum.data = null;
function doSum()
{
var url = "simple_ajax_server.php";
var data = "val1=" + document.getElementById("val1").value + "&val2=" + document.getElementById("val2").value;
var method = 'GET';
var async = true;
doAjax(url, method, async, displaySum, data);
}
</script>
</body>
</html>
// Common function to initialize XML Http Request object
function getHttpRequestObject()
{
// Define and initialize as false
var xmlHttpRequst = false;
// Mozilla/Safari/Non-IE
if (window.XMLHttpRequest)
{
xmlHttpRequst = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpRequst = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttpRequst;
}
// Does the AJAX call to URL specific with rest of the parameters
function doAjax(url, method, async, responseHandler, data)
{
// Set the variables
url = url || "";
method = method || "GET";
async = async || true;
data = data || null;
if(url == "")
{
alert("URL can not be null/blank");
return false;
}
var xmlHttpRequst = getHttpRequestObject();
// If AJAX supported
if(xmlHttpRequst != false)
{
// Open Http Request connection
if(method == "GET")
{
url = url + "?" + data;
data = null;
}
xmlHttpRequst.open(method, url, async);
// Set request header (optional if GET method is used)
if(method == "POST")
{
xmlHttpRequst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
// Assign (or define) response-handler/callback when ReadyState is changed.
xmlHttpRequst.onreadystatechange = responseHandler;
// Send data
xmlHttpRequst.send(data);
}
else
{
alert("Please use browser with Ajax support.!");
}
}
<?php
$val1 = (int)$_REQUEST['val1'];
$val2 = (int)$_REQUEST['val2'];
echo $val1 + $val2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment