In the Web 2.0 it is familiar to create new services. In Germany the Web 2.0 is also called “Mitmach-Web” (join-in-web). And there is a other transformation in the scene: With Javascript (and that what is called Ajax – I call it in german always “Webwaschmittel”) more and more static websites becomes dynamically web applications – to use like normal desktop applications. But to have an interactive website, which behaves similar to a desktop application (giving response in no time, show informations and take the user into its own hand). The one thing webdesigners and web-developers do to make a website interactive and behaves like an application is to use Javascript. Javascript is the mean of choice but there exists several Javascript-Frameworks which helps the user to write clean and short Javascript-Code with a great functionality.
On the backend-side (server-side) the programmers have done also many development and engineering in the last years. Several Frameworks have been established (Symfony, CodeIgniter, Ruby on Rails, Zend, Flow3 and so on – more about frameworks in the iX special “Web on Rails“). I am using CodeIgniter because it is a really leightweight and nice to use framework with many functionality, but the latitude to program and design your application as you will (means: with very few restrictions and a very small footprint).
In this little HowTo I want to show you how to build a little CodeIgniter REST-like API (only an example with one controller) and use it via Javascript (ajax with jQuery). The REST-API (Representational State Transfer – Advanced Programming Interface) is an idea, a way how to provide information and data as an service to the web, using the HTTP-protocol given mechanisms (like POST-data, GET-data, …). I write knowingly “REST-like”, because it is no easy work to create a full and dynamically usable REST-API. The MVC-Pattern-Design from CodeIgniter helps you to build Controller which can behave REST-like. But still programming a controller and let them return a header and some data is not the whole idea of a REST-full API.
To learn what a REST-API is or how it works: have a look at “A RESTful Web service, an example” by Paul James. There are also a german PDF “REST Web Services – eine Einführung” available from OIO (Orientation In Objects – a german software development company).
I also used two other tutorials from the web to inform myself about form validation with Ajax. You can find them at the end of the article among “Sources”.
Now I want to show you in an easy way how to build one little web service which validates something for you and send a response. A Javascript snippet send a call to the CodeIgniter Controller, the Controller do something and send an response. The answer will be shown up on the front end without relaoding the whole website. So it is good for a site with a PHP-Backend (via the REST-API) because it can be used from others later (maybe from outside or from company-internal services).
This code splitting: using Javascript for the request and do the validation in PHP and sending an response makes your application more secure, because if you writes your validation all in Javascript inside the HTML-code, a attacker can use this information. And you need in all cases (also when you wants to validates all with Javascript inside the HTML-code and also with the scenario explained in this article) a PHP-function to validate the data you gets from outside before it will be inserted maybe in a database. Because a attacker can build a own website, using your site and deletes the Javascript code and then sending some shit to your application.
It is some of the most important security-rules when you have an application with data coming from outside your application to test them in all cases. The application has to verify that the data are as expected and that the length is like expected. Just to think all users are nice and it is enough to tell them “this string has to be maximal 128 characters long” and not to verify is a naive way.
But now coming to the things you need to build a Ajax form validation with jQuery and a REST-like API built with CodeIgniter.
What do you need?
You need a CodeIgniter installation. You need a Controller (which represent the REST-like API), a HTML-Website, jQuery and a little Javascript snippet. For testing I used a simple HTML-Website (no site provided by CI – so in this example I just use CI for the validation-response).
- Your Controller must have the name: service.php and must have (in this example) a function exists()
- The service has be available in: system/application/controller/
- The simple HTML-File for test this web-service has to be stored in the same directory as the CI index.php.
- The HTML-File itself. I named it: template.php (it has an php-suffix, but it is still a HTML-site).
Let´s start with the HTML-File and some Javascript.
The HTML-File and Javascript-Code
First of all create an HTML-File. I using one created with YAML. In the header of the HTML-File you have to link to jQuery (local stored or from the web), to use their functions.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
Then you put these Javascript Snippet in the head.
$(document).ready(function () {
var validateUsername = $('#validateUsername');
$('#username').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif" height="16"
width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'index.php/api/service/exists/',
data: 'username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
What this all stands for and the parts of the code are explained in the source jQuery for designers “Using Ajax to validate forms” below. You see at line 7 a little grafic is loaded. You have to put this image in your images-directory. A Ajax-Load-Image (also called ajax spinner) in your style can be downloaded at ajaxload.info. This grafic indicates activity when load data via Ajax.
In the middle of the code you see the $.ajax({})-part. This are the data which will be send to your CodeIgniter REST-like API to validate them. The url is the uri-segment of your CodeIgniter-URL. This is, why the template.php file has to be stored where the CI index.php is. This will later be unnecessary when you load your website via CI, but is necessary in this example because we work with this simple template.php-File instead of using the CI framework for providing the test-site.
The part exists is the function inside your CI-Controller “service“. As you can see we pass the data in JSON-format. So the response later has also to be in JSON. And we put the data via HTTP “post” to the CI service, so we have to read later the data from the PHP $_POST[]-variable.
As you know, CI normally gets the data via GET over the URL (in the uri-segments like: controller/function/param1/param2). This also works with this JScript. Normally via Ajax and REST-API you put the data via POST. If you want to put it via the URL you have to change the script above. Delete the lines for set “data” and “type” and transofrm the url like this:
url: 'index.php/api/service/exists/' + t.value
The next thing is the HTML-snippet (with the IDs from above, used in the Javascript). This is the base for using the Javascript, sending the value in the input-field and display the response from the CI-Controller.
The HTML-Code
This is the HTML-Code inside our template.php to few an input-form-field and can view the response from CI and the loading-spinner. The spinner and the validation-response is shown in the span with the ID #validateUsername.
<div>
<label for="username">Username, valid: a-z.-_</label>
<input type="text" name="username" value="" id="username" />
<span id="validateUsername"><?php if ($error) { echo $error['msg']; } ?></span>
</div>
No we have the base to call the CI function, which makes the validation (or whatever you want) and send a response.
The CodeIgniter controller and function – The REST-like API
This is a primitive Controller, which only checks if a parameter is given or not and sending a response. You can do in this function much more, like doing a database query.
/**
* Checks whether a given string is valid or not
* @param string $value A given value when you call the function via PHP
* @return string A JSON encoded array
* @author UK
*/
public function exists($value=null) {
$value = $_POST['username']; //POST-Data from the Javascript
$response = array();
//If you does not get an response, you can use this code
//to test if the JScript calls the controller correctly
/* $filename = "/the/path/to/your/file.txt";
$handle = fopen($filename, "w+");
fwrite($handle, $value);
fclose($handle); */
if (empty($value)) {
$response = array(
'ok' => false,
'msg' => 'invalid username'
);
} //if - empty
else {
$response = array(
'ok' => true,
'msg' => 'valid username'
);
}
header('Content-Type: application/json');
echo json_encode($response); //send the response to the caller
} //exists
Only one thing is important. That the Ajax-caller can get the response, the callee have to send an http-header (that now coming JSON-encoded data) and then just send (echo) the data. This are the last two lines. A PHP-return is not enough, because this returns the data to the PHP-internal caller (which is here the CI-Framework, coming over the index.php). But you need to put the data via http to the frontend-website and this is, what echo do.
That´s it.
Now you have an REST-like API (your Controller) and have a nice input-field which let the data on change validate from the CI Controller.
The only disadvantage is, that you need for every input-field you want to validate a little Javascript snippet in the site-header. But maybe you can write them all together in a little js-File and include one file. Maybe the code for sending the value and showing the grafic can be written down in a little javascript-function, so that every snippet for every input-field can reuse these things. So you can minimize the overhead.
Sources
“Using Ajax to validate forms” at jqueryfordesigners.com
“jQuery for Designers – Ajax Form Validation Example” at jqueryfordesigners.com
“A quick Code Igniter and jQuery Ajax Tutorial” at mrforbes.com
Verwandte Beiträge:























Thanks for you post. It was very helpfull for me, becouse I isn’t very familar with javascript. Used this tip with kohana. Note if your controller extends Template_Controller you should create your own one and overload _render method
Thanks for the overload-tip. Nice idea …