Archive for Ajax with PHP

Ajax Frameworks, Tools and Libraries with PHP

Ajax Frameworks, Tools and Libraries with PHP

 

Xajax - PHP Class Library

What Xajax is:

‘xajax is an open source PHP class library that allows you to easily create powerful, web-based, Ajax applications using HTML, CSS, JavaScript, and PHP. Applications developed with xajax can asynchronously call server-side PHP functions and update content without reloading the page.’

How it works:

‘The xajax PHP object generates JavaScript wrapper functions for the PHP functions you want to be able to call asynchronously from your application. When called, these wrapper functions use JavaScript’s XMLHttpRequest object to asynchronously communicate with the xajax object on the server which calls the corresponding PHP functions. Upon completion, an xajax XML response is returned from the PHP functions, which xajax passes back to the application. The XML response contains instructions and data that are parsed by xajax’s JavaScript message pump and used to update the content of your application.’

Find out more about Xajax at the XajaxProject website - or visit their sourceforce project page

 

 

Sajax - Tool

What Sajax is:

‘Sajax is a tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call ASP, Cold Fusion, Io, Lua, Perl, PHP, Python or Ruby functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.’

How it works:

‘Our toolkit creates a JavaScript stub function that calls functions you export from your script. It handles all the connection details and calls a callback function of your design when the data is available.’

Find out more about Sajax at the ModernMethods
website.

 

 

Ajax HTML from PEAR - Libraries

This is a PHP and JavaScript package available through the official PEAR website. For simple examples tutorials, visit the package authors website. To download this package, visit the HTML_AJAX Package page on PEAR.

 

 

XOAD - PHP Based Ajax Framework (formerly known as NAJAX)

‘XOAD is a PHP based AJAX/XAP object oriented framework that allows you to create richer web applications.

XOAD has many benefits:

it uses JSON and native PHP serialized objects to communicate,
special attention has been paid to security,
supports server side events (observation),
client side events (XOAD Events),
server and client extensions,
HTML manipulation (extension),
Caching (extension).’

Find out more about XOAD at the XOAD
Wiki website
.

 

 

AjaxAC - PHP Based Ajax Framework

‘AjaxAC is an open-source framework written in PHP, used to develop/create/generate AJAX applications. The fundamental idea behind AJAX (Asynchronous JavaScript And XML) is to use the XMLHttpRequest object to change a web page state using background HTTP sub-requests without reloading the entire page. It is released under the terms of the Apache License v2.0.’

‘The basic idea behind AjaxAC is that you create an AjaxAC application, which in itself contains a number of action handlers and event handlers. An application in this context might mean an entire web site powered by AJAX, or it could mean a subset of a form (such as the CountryRegionCityJax example, which could be a small part of a signup form, for example).’

Find out more about the AjaxAC Framework

 

 

CPAINT - Ajax Toolkit (Cross-Platform Asynchronous INterface Toolkit)

What CPAINT is?

‘CPAINT (Cross-Platform Asynchronous INterface Toolkit) is a multi-language toolkit that helps web developers design and implement AJAX web applications with ease and flexibility. It was originally born out of the author’s frustration and disappointment with other open-source AJAX toolkits. It is built on the same principles of AJAX, utilizing JavaScript and the XMLHTTP object on the client-side and the appropriate scripting language on the server-side to complete the full circle of data passing from client to server and back.’

Some Features:

‘Flexibility - built for small and enterprise applications
100% OOP approach
Supports multiple scripting languages (ASP & PHP)
Unified JavaScript file for all functions
Supports both Remote Scripting and XML
Supports both local & remote functions
Single or multiple XMLHTTP objects
Returns backend data as text or as a JavaScript XML/DOM document object
Can support both POST & GET requests
Backend proxy functions for accessing remote functions and data
Tested with all major browsers
Distributed under the GNU GPL & LGPL ‘

Find out more at the CPAINT website or visit their SourceForge Project page.

 

This list is in no way exhaustive.

Comments

Ajax with PHP using responseXML

I’ll start off with a very basic technique of using Ajax with the responseXML (not responseText). responseXML basically means that the returned values is in an XML format. The other option would be to use responseText which in many cases would be the simplest method. But true Ajax uses XML (as the X in the name suggests).

OK, let’s dive right into some code.

First we want to create the XML HTTP Request Object (this is always required!)

var http = createRequestObject();

function createRequestObject() {
	// find the correct xmlHTTP, works with IE, FF and Opera
	var xmlhttp;
	try {
  	xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(e) {
    try {
    	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e) {
    	xmlhttp=null;
    }
  }
  if(!xmlhttp&&typeof XMLHttpRequest!="undefined") {
  	xmlhttp=new XMLHttpRequest();
  }
	return  xmlhttp;
}
  

 

In the above we have used some error checking to see which method works with the users browser, Internet Explorer uses ActiveX while other browsers don’t. The try(), catch() functions are JavaScript’s way of finding errors and can be used to control any errors which might be returned to the users browser.

 

Now we’ll create the function which will handle sending the request to the Server Script (and pass values we require):

function sendRequest() {
	var name = document.getElementById("name").value;
	var email = document.getElementById("email").value;
	var rnd = Math.random();
	if(name.length >0 && email.length >0) {
		name=escape(name);
		email=escape(email);
	try{
    http.open("GET", "index_inc.php?name="+name+'&email='+email+'&rnd='+rnd, true);
    http.setRequestHeader('Content-Type',  "text/xml");
    http.onreadystatechange = handleResponse;
		http.send(null);
	}
	catch(e){
		// caught an error
		alert('Request send failed.');
	}
	finally{}
		// disable button until end of response
		document.getElementById('go').disabled = true;
		document.getElementById('go').value = "Hold On";
		// hide any previous returned values
		document.getElementById('returned_value').style.display="none";
	} else {
		alert("please complete both fields first");
	}
}
  

 

In the above snippet we first get the values we plan on sending to the Server, in this case ‘name’, ‘email’ and also a random number. The random number is used to help prevent browsers caching the any previous requests.

We then check the length of the values we will pass (we check that both name and email contain more than 1 character).
Using http.open we set the GET value as the method and the script path along with the values mentioned above.
The set the request header as content type text/xml then send the request to the server script. Notice we use ‘http.onreadystatechange = handleResponse;’ which tells the script to call the handleResponse function once the state has changed (we will get to this function next)

Once we try and catch any errors we do some cosmetic stuff like disable the Submit button and hide any previous returned values.

Handle the response from the server script:

function handleResponse() {
	try{
    if((http.readyState == 4)&&(http.status == 200)){
    	var response = http.responseXML.documentElement;
    	var n = response.getElementsByTagName('name')[0].firstChild.nodeValue;
    	var e = response.getElementsByTagName('email')[0].firstChild.nodeValue;
    	var r = response.getElementsByTagName('random')[0].firstChild.nodeValue;

    	// write out response
      document.getElementById("returned_value").innerHTML =
      '<br /><strong>Returned:</strong> <a href="mailto:'+e+
      '">'+n+'</a> ('+e+') <strong>Random:</strong> '+r;

      // re-enable the button
      document.getElementById('go').disabled = false;
      document.getElementById('go').value = "Submit";
      document.getElementById('returned_value').style.display="";
		}
  }
	catch(e){
		// caught an error
		alert('Response failed.');
	}
	finally{}
}

In the above function we retrieve the response from the server script (the XML data) and get the values we want to use.

We then use the ‘document.getElementById(”returned_value”).innerHTML = ….etc’ to write the data to the browser.

Then enable the submit button… we’re done with the request and response now!!

OK, now to see the form used to get the values (name and email) from the user:

<style type="text/css">
body{font-family:arial;font-size:11px}
fieldset{text-align:center;width:550px;border:1px solid #387CAF}
legend{font-weight:bold;color:#387CAF;font-size:17px}
#returned_value{text-align:center;font-size:12px;}
#go, input{border:1px solid #387CAF;background:#FFF}
</style>

<body onLoad="document.getElementById('name').focus()">
	<fieldset>
		<legend> Ajax example (with responseXML) </legend>
		<br />
		<label>Name: <input type="text" id="name" name="name"/></label>&nbsp;
		<label>Email: <input type="text" id="email" name="email"/></label>&nbsp;
		<input type="button" value=" Submit " id="go" onClick="sendRequest()"/>
		<br /><br />
	<span id="returned_value"></span>
	</fieldset>
</body>

Here is the XML which the server script returned to the browser:

< ?xml version="1.0"?>
<user>
  <name>stuart</name>
  <email>stuartc1@hotmail.com</email>
  <random>0.98789</random>
</user>

Important: Internet Explorer handles extra white space between XML elements fine, but other more strict browsers do not. So please check the format of your XML if you have problems. There are some JavaScript functions around which fix white space problems! In some cases though you can use the plain old responseText without the worry!

Take a look at this Ajax code in action
View the full source code.

Comments (12)

· Next entries »