To clearly illustrate how easy it is to access information from a database using AJAX, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, we do the ground work. We are using MySQL database and the database is test.
We create a table using the following command.
CREATE TABLE 'ajax_example' (
'name' varchar(50) NOT NULL,
'age' int(11) NOT NULL,
'sex' varchar(1) NOT NULL,
'wpm' int(11) NOT NULL,
PRIMARY KEY ('name')
We insert the following data into this table using the following SQL statements:
INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);
INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);
INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);
INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);
INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);
INSERT INTO 'ajax_example' VALUES ('Julie', 35, 'f', 90);
Now the database has been created so we now create the client side file. In order to check the proper functioning of AJAX it is necessary to have data in the database so that on proper execution we get the results on to the client side. This method ensures the easiest way of calling AJAX with the use of database and any errors if occurring could be traced as well.
Client Side HTML File
The client side file is ajax.html, and it will have the following code:
The result will be displayed in theajaxDiv section.
Server Side JSP File
Since our client-side script is ready so have to write our server-side script, which will fetch data from the database and will send it back to the client. Put the following code into the file "fetch.jsp".