Archive for ajax-with-php

Simple Ajax using Prototype. Part 2

Ajax Updater - Update a DOM element ID from a Server Script

This example is probably the simplest example you will ever find.
We are going to use the prototype feature ‘ajax.Updater’ (see part one for more details on prototype).

ajax.Updater allows you to specify an element ID and script URL - and whatever the script URL prints will appear in your element ID. Simple as that.

The example below simply returns the Server time each time the button is clicked.

I’m not going to explain this bit by bit as it is just so easy to grasp.

Remember, you will need the prototype library in order to use this!

Here is the HTML/JavaScript code:


And now the PHP code:

updateme.php


The above example has no real use, but in the real world there are many things which can be done. For example I recently wrote an automatic session log-out script, which automatically kills the session after a given period and send the user back to the login page (very handy for secure sites). I’ll post that script up soon.

Comments (2)

Simple Ajax using Prototype. Part 1

This is part of one of many such tutorials covering Ajax with Prototype.

If you do not want to get your hand to dirty with custom Ajax code, then using the extremely handy toolkit from prototype may be perfect.
Prototype is a very well written JavaScript framework/toolkit and come with an Ajax class to make things nice and easy.

In this simple example I’ll show you just how easy Ajax calls are. But you will need to have your own copy of prototype (its free!).

On a side note… if you like fancy JavaScript effects, you can extend prototype with another library called script.aculo.us - I promise, with these you will have endless hours of fun!!

On with the example
I’ve attempted to simplify things as much as possible. In this tutorial we will type some text into a standard form field, hit a button and see the results appear below. In the background, our button click will trigger our JavaScript function, and pass the text through Ajax to a server-side PHP script. This PHP script will write our text back to an other JavaScript function on our page and print the text out on the screen.

First we include our prototype library:


Then we create two of our own functions, the first one is the main script which passes our text to the Server (PHP script in this case). The second function handles the response from the PHP script and prints the results to the browser.


In the getResponse function above, noticed the function call $(’result’) - this is a feature of prototype which basically replaces ‘document.getElementByID(’result’)’.

Yes, that is all we need in terms of JavaScript. I told you it was simple!!

Next we have the form:


Nothing fancy with the above. In order to call our JavaScript functions, we are using the ‘onClick’ event of the button.
We are passing in two values here; first the server-side script file ‘parse.php’ and the value we want to send.
We must pass in the paramater name and value (for example: ‘val=myvalue’, just like any querystring!), the parameter name in the case is ‘val’ and the value is the text in our text field. We refer to this value using another prototype function $F() which is really just ‘document.getElementById(’myval’).value’.

On the server-side, our PHP script takes the value we passed $_GET['val'] and prints it back to us as ‘You entered: yourvalue’ (where ‘yourvalue’ is what your entered in the text field!).

parse.php


This is a very simple example of using just one of prototypes Ajax features, there are many more to explorer which I will cover soon.

Have fun!

Comments (6)

AJAX generic form parser

AJAX Generic Form Parser - With Validation:

In this tutorial I’ll show you a simple method to pass any HTML form through AJAX without the need to hard code all form fields into the JavaScript or Server Side Script. Using this simple piece of JavaScript you can reuse it as is with any form, saving a lot of time. I’ve even added basic validation to certain form element types (which would be expected).

Okay, straight to the main JS code.

The JavaScript code above is split into 4 functions, here is an overview of what each function does.

createXMLHttpRequest() - This is the function which will establish the AJAX connection object, this is called as soon as the JS file is loaded.

sendRequest() - This function is the one which is called when the form is submitted. This function requires (passed in) the ‘Form Object’ and the ‘File Name’ of the script which will receive the form data. When this function has been called, it takes the form object and passes it to the JS function getForm() which in turn parses the whole form extracting all the data. sendRequest() then takes the open AJAX connection and passes all the data to the PHP file form processing. Finally when the request from the PHP server script is returned, it writes out the reply to an element on the screen with the div ID ‘results’.

getForm() - This is the magic, this function reads through the whole form and extracts the field data before returning it back to sendRequest(). It handles radio, text, password, textarea, select and checkbox field types. It even looks for validation requests on text, password and textarea fields (which is enabled by using title=”required” in the form element).

Simple :)

Next is a very simple form with a mixture of field types and validation requests (nothing fancy here). Also included at the bottom is the div which prints out the results to the browser.

As you can see the form trigger which calls the AJAX actions is set in the button using the onClick method. Also note I’ve added title=”required” to the ‘textOne’ field - this means the user will not be able to submit the form unless this field contains a value.

Finally here is a very stripped down Server script in PHP which takes the form values and returns them formatted back to the JS (you could do anything with the data at this stage!).

process.php

You could easily change the above to generate an email or add the form data to a database, the above example will echo out the results which are passed back to the div tag below the form.

There you have it, short and sweet (I hope) - I’ve intentionally kept the example scripts to a minumum but with still enough to be useful. Please feel free to take this and mess around with it.

Have Fun!!

Comments (6)

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 off

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 =
      'Returned: '+n+' ('+e+') Random: '+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:





	
Ajax example (with responseXML)    

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


< ?xml version="1.0"?>

  stuart
  stuartc1@hotmail.com
  0.98789

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 (13)

Bad Behavior has blocked 648 access attempts in the last 7 days.