Simple Ajax Library

Krstevski 0 Tallied Votes 900 Views Share

This simple library containing some methods of Ajax.

Example about addContent(url, target):
With this function you can change the content of the someone DIV tag.

E.g:
index.php

<html>
<head>
	<title>Untitled Document</title>
	<script type="text/javascript" src="ajax.js"></script>
</head>

<body>
	<div id="test">
        <a href="javascript: addContent('test.php', 'content')"> Change </a>
    </div>
    
	<div id="content">
    	<label> This is just test... </label>
    </div>
    
</body>
</html>

test.php

<?php
   echo "Simple Ajax Library Example!";
?>

When you click on "Change" then the content of the div tag named "content" will change to what you have written in the file (In this example, test.php -> Simple Ajax Library Example!).

The functions getResults(str, url, target) and suggest(str, url, target) are Ajax methods with more arguments.

str = input string
url = The url or resource file
target = id name of div tag where you want to display the results

----

This library is nothing special, but can be very useful and saves much time.
The library is tested only with PHP.
Every remark are welcome and if you have any idea of upgrading / changing this library you can do it.

Thanks, SkyDriver.

// JavaScript Document

/*
	@Author SkyDriver - Damjan Krstevski
	@Country/City: Macedonia, Skopje
	@Date 26/2/2010 - 10:31 AM
	@Description: Ajax library...
	@License: Freeware, you can use, change and redistributed this library.
*/

var xmlhttp;

/// <summary> Changing the contents of a tag </summary>
/// <param name="url"> URL/Resource File with content who want to change </param>
/// <param name="target">ID name of DIV tag where you want to make change </param>
/// <api> javascript: addContent('myfile.php', 'mydivid'); </api>
function addContent(url, target) {
	try {
		xmlhttp = GetXmlHttpObject();
		if (xmlhttp == null) {
			alert (error);
			return;
		}
		xmlhttp.open("GET", url, false);
		xmlhttp.send(null);
		document.getElementById(target).innerHTML = xmlhttp.responseText;
	} catch (e) {
		alert("An error occurred.\nDetails: " + e);
	}
}


/// <summary> Reading records from database/file and changing the contents of a tag </summary>
/// <param name="str"> Input string (search string) </param>
/// <param name="url"> URL/Resource File with the code for getting the information from the database/file </param>
/// <param name="target">ID name of DIV tag where you want to show results </param>
/// <api> onClick="getResults('my search string', 'getResults.php', 'mydivid')" </api>
function getResults(str, url, target) {
	xmlhttp = GetXmlHttpObject();
	if (xmlhttp == null) {
		alert ("Your browser does not support XMLHTTP!");
		return;
	}
	url = url + "?q=" + str;
	url = url + "&sid=" + Math.random();
	xmlhttp.open("GET", url, false);
	xmlhttp.send(null);
	document.getElementById(target).innerHTML = xmlhttp.responseText;
}


/// <summary> Help with search (suggest) </summary>
/// <param name="str"> Input string (search string) </param>
/// <param name="url"> URL/Resource File with the code for getting the information from the database/file </param>
/// <param name="target">ID name of DIV tag where you want to show results </param>
/// <api> onkeyup="suggest(this.value, 'getSuggest.php', 'mydivid')" </api>
function suggest(str, url, target) {
	if (str.length == 0) {
		document.getElementById(target).innerHTML = "";
		return;
	}
	xmlhttp = GetXmlHttpObject();
	if (xmlhttp == null) {
  		alert ("Your browser does not support XMLHTTP!");
  		return;
	} 
	url = url + "?q=" + str;
	url = url + "&sid=" + Math.random();
	xmlhttp.open("GET", url, false);
	xmlhttp.send(null);
	document.getElementById(target).innerHTML = xmlhttp.responseText;
}

function GetXmlHttpObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

Dani AI

Generated

A useful, compact starting point from . The one thing that will cause trouble in modern pages is the use of synchronous XHR: it blocks the main thread, causes UI freezes under slow networks, and has been deprecated for main-thread use. (developer.mozilla.org)

Modernize by switching to asynchronous patterns (promises / async-await) or the Fetch API; it is the recommended, more flexible replacement for XHR and works well with service workers and modern features. Always check the response status before using the body, and build query strings with encodeURIComponent to avoid broken parameters. For content insertion, prefer textContent for plain text or sanitize server HTML before assigning to innerHTML — untrusted HTML is a common XSS vector. (developer.mozilla.org)

For autocomplete/suggest, debounce keystrokes and cancel in-flight requests to prevent race conditions and wasted work. Use AbortController to cancel fetch requests when a newer query starts (and ignore AbortError in the catch). That keeps the UI responsive and avoids stale responses overwriting newer ones. (developer.mozilla.org)

Short, practical checklist and examples:

  • Replace sync open(..., false) calls with fetch/async functions.
  • Use encodeURIComponent for query values.
  • Avoid a single global XHR object; scope requests locally.
  • Debounce user input (200–300 ms) and abort previous requests for suggest.
  • Prefer JSON for structured responses and sanitize any HTML.

Example (minimal):

async function addContent(url, target) {
  const res = await fetch(url, { cache: 'no-cache' });
  if (!res.ok) throw new Error(res.status);
  document.getElementById(target).innerHTML = await res.text(); // sanitize if untrusted
}
let timer, controller;
function suggest(q, url, target) {
  clearTimeout(timer);
  if (controller) controller.abort();
  if (!q) return (document.getElementById(target).textContent = '');
  timer = setTimeout(async () => {
    controller = new AbortController();
    try {
      const res = await fetch(url + '?q=' + encodeURIComponent(q), { signal: controller.signal });
      if (res.ok) document.getElementById(target).innerHTML = await res.text();
    } catch (e) { if (e.name !== 'AbortError') console.error(e); }
  }, 250);
}

These changes keep the library simple but make it safe and responsive for modern browsers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.