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)

Learning Ajax Book : Ajax and PHP

Ajax and PHP - Building Responsive Web Applications

Packt Publishing have been kind enough to send me an copy of their Ajax and PHP book. I now have dedicated place for this book on my work desk, and expect it’ll come in extremely handy when building my next Ajaxed and PHP based application.

The book is aimed mainly at developers who have some HTML, PHP and JavaScript knowledge - but you do not need to be an expert in any of these by any standard. The book starts off by explaining exactly what Ajax is and how it works (contains many descriptive diagrams to make this clear), also covers the basics of how HTTP and HTML work to make it more complete. Don’t worry, it covers these explanations perfectly - not to in depth and not to sparse, in my opinion they have got the concentration perfect.

The book is split into 10 Chapters, covering the most common uses of Ajax (DOM, XML, Form Validation, Chatting, Charting, RSS , Drag and Drop etc.)

Before I give a run down of each chapter I would just like to say this. I’ve read many computer programming books over the years, many great and some not so good. In comparison, I’d put this book in my top 5. My rating for this book is 9 out of 10.

More details on Ajax and PHP

Paperback: 275 pages
Release date: March 2006
ISBN: 1904811825
Authors: Cristian Darie, Bogdan Brinzarea, Filip Chereches-Tosa and Mihai Bucica

AJAX and PHP: Building Responsive Web Applications is the most practical and efficient resource a reader can get to enter the exciting world of AJAX. This book will teach you how to create faster, lighter, better web applications by using the AJAX ingredients technologies to their full potential.

In Detail
Assuming a basic knowledge of PHP, XML, JavaScript and MySQL, this book will help you understand how the heart of AJAX beats and how the constituent technologies work together. After teaching the foundations, the book will walk you through numerous real-world case studies covering tasks you’ll be likely to need for your own applications:

  • Server-enabled form-validation page
  • Online chat collaboration tool
  • Customized type-ahead text entry solution
  • Real-time charting using SVG
  • Database-enabled, editable and customizable data grid
  • RSS aggregator application
  • A server-managed sortable list with drag&drop support using the script.aculo.us
    JavaScript toolkit

The appendices guide you through installing your working environment, using powerful tools that enable debugging, improving, and profiling your code, working with XSLT and XPath.

What you will learn from this book

Chapter 1: AJAX and The Future Of Web Applications is an initial incursion into the world of AJAX and the vast possibilities it opens up for web developers and companies, to offer a better experience to their users. In this chapter you’ll also build your first AJAX-enabled web page, which will give you a first look of the component technologies.

Chapter 2: Client-Side Techniques with Smarter JavaScript will guide you through the technologies you’ll use to build AJAX web clients, using JavaScript, DOM, the XMLHttpRequest object, and XML. While not being a complete tutorial for these technologies, you’ll be taken to the right track of using them together to build a solid foundation for your future applications.

Chapter 3: Server-Side Techniques with PHP and MySQL completes the theory foundation by presenting how to create smart servers to interact with your AJAX client. You’ll learn various techniques for implementing common tasks, including handling security and error handling problems.

Chapter 4: AJAX Form Validation guides you through creating a responsive, modern form with real-time validation based on server data.

Chapter 5: AJAX Chat presents a simple online chat that works exclusively using AJAX code, without Java applets, Flash code, or other specialized library, as most chat applications work these days.

Chapter 6: AJAX Suggest and Autocomplete builds a Google-suggest like feature, that helps you find PHP functions, and forward you to the official help page for the chosen function.

Chapter 7: SVG (Scalable Vector Graphics) is a text-based graphics language that can be used to draw shapes and text. (SVG is supported natively by Firefox 1.5, and requires a SVG plugin with other browsers). In this case study you learn how to implement a realtime charting solution with AJAX and SVG.

Chapter 8: AJAX Grid teaches you how to build powerful updatable data grid. You’ll learn how to parse XML documents using XSLT to generate the looks of your grid.

Chapter 9: AJAX RSS Reader uses the SimpleXML PHP library,
XML and XSLT, to build a simple RSS aggregator.

Chapter 10: AJAX Drag and Drop is a demonstration of using the script.aculo.us framework to build a simple list of elements with drag&drop functionality.

Appendix A: Configuring Your Working Environment teaches you
how to install and configure the required software: Apache, PHP, MySQL, phpMyAdmin.

Who this book is written for
This book is for web developers willing to build better web applications. A basic knowledge of PHP, XML, JavaScript and MySQL, or a strong will to learn-as-you-type, is assumed.

If you are interested in buying this book, I suggest buying it directly from the publishers as they seem to have the best discount right now.

Download the sample chapter: Chapter 1: AJAX and The Future Of Web Applications

Comments (2)

Ajax Tutorial

Here is another very interesting Ajax resource well worth a read. This article give some nice examples of things you can do with Ajax, some tutorials and also explains the history of Ajax. The article is several months old and you may already have came across it before - but it certainly deserves a mention here. Check out DHTMLNirvana’s Ajax - What is it good for?

Comments off

AJAX and Accessibility

Just read an interesting article over at sitepoint by James Edwards. Titled AJAX and Screenreaders: When Can it Work?

We’ve all heard a great deal of buzz about AJAX in the last few months, and with this talk has come a legion of articles, tips, presentations and practical APIs designed to explore the possibilities and try to arrive at best-practice techniques. But, for all of the excitement and hype, still very little has been said on the subject of AJAX and accessibility.

Nice thought provoking article.

Comments off

« Previous entries · Next entries »

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