Ajax

The handling functions I use for asymetric Javascript requests.

I usually use these with my PHP Action() class that generates XML responses in the format I like them.

Source code

Ajax request

// Do an Ajax request.
// Vars:
//   ajax_link *(str) - HTTP page to load (either an absolute URL or new query args for the current page starting with ?).
//   ajax_function (str) - Function to receive the HTTP page text when it loads.
//   raw_response (bool) - Supply a raw response to ajax_function (don't run it through ajax_response() to get variables as an array).
// Returns:
//   true on success.
//   false + alert() on failure.
function ajax(ajax_link, response_function, raw_response)
{
	var http = http_request(); // No HTTP object, so make one.
	if (http == false)
	{
		alert('AJAX Error: Background requests are not supported in your browser.');
		return false; // Does not work in this browser.
	}

	// Absolute current path.
	if (ajax_link.substr(0, 4) != 'http') ajax_link = window.location.protocol + '//' + window.location.hostname + window.location.pathname + ajax_link;

	// Add the time to the end of the request (to stop browsers caching).
	if (ajax_link.indexOf('?')) ajax_link = ajax_link + '&quick&ajax&time=' + time();
	else ajax_link = ajax_link + '?quick&ajax&time=' + time();

	// Setup the request and catch access denied errors etc.
	try { http.open('GET', ajax_link, true) }
	catch (e) { alert('AJAX Error: ' + e.description); return false; }

	// Run the specified function when the page has loaded.
	// Return the HTTP as text, or as XML if xml_response is true, after processing the response with ajax_response().
	if (response_function)
	{
		if (raw_response)
		{
			http.onreadystatechange = function()
			{
				if (http.readyState == 4)
				{
					if (http.status == 200) if (http.responseText.length > 0) response_function(http.responseText);
					else if (http.status > 0) alert('AJAX Error: Endpoint returned error code ' + http.status + '.');
				}
			}
		}
		else
		{
			http.onreadystatechange = function()
			{
				if (http.readyState == 4)
				{
					if (http.status == 200)
					{
						if (http.responseText.length > 0)
						{
							var response_array = ajax_response(http.responseText);
							if (typeof response_array == 'object') response_function(response_array);
						}
					}
					else if (http.status > 0) alert('AJAX Error: Endpoint returned error code ' + http.status + '.');
				}
			}
		}
	}

	// Send the request and catch errors etc.
	try { http.send(); }
	catch (e) { alert('AJAX Error: ' + e.description); return false; }

	return true;
}

// Return the correct object for AJAX (different versions of different browsers).
function http_request()
{
	if (typeof XMLHttpRequest != 'undefined') return new XMLHttpRequest();

	try { return new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e)
	{
		try { return new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (e) { return false; }
	}

	return false;
}

Process the XML response

If you wish for your Ajax request to send some information back to the current page, you can set a function via the ajax_function var which will receive that response.

If you don't set raw_response = true in ajax_request(), the response is assumed to be an XML response in the following format:

<?xml version="1.0" encoding="utf-8" ?>
<response>
	<status>success</status>
	<var1>Var 1</var1>
	<var2>Var 2</var2>
	<var3>Var 3</var3>
</response>

This XML response is automatically run through the following ajax_response() function, which uses my XML parser to turn it into an array of variables, and return it to the function specified in ajax_request()'s ajax_function var.

// Process an Ajax XML response (usually sent by an Autostyle Action object).
// Vars:
//   response_string *(str) - XML string containing variables (top-level container must be <response>)
// Returns:
//   Array of variables specified in XML string on success.
//   false + alert() on failure.
function ajax_response(response_string)
{
	response_array = xml_to_array(response_string);
	if (typeof response_array == 'object')
	{
		if (typeof response_array['response']['status'] == 'string')
		{
			if (response_array['response']['status'] == 'success') return response_array['response']; // Return an array of variables.
			else if (typeof response_array['response']['explanation'] == 'string') alert(response_array['response']['result'] + ' ' + response_array['response']['explanation']);
			else if (typeof response_array['response']['result'] == 'string') alert(response_array['response']['result']);
			else alert('Error.');
			return false;
		}
		else
		{
			alert('AJAX Error: Top-level container in XML response must be .');
			return false;
		}
	}
	else return false;
}

// Generate Unix time.
function time() { return Math.round(new Date().getTime()/1000); }