Sending List box option to the server asynchronously

In this article, we will learn how multiple items selected from the list box are sent to the server asynchronously.

For this article, we will make three files namely:

  • listajax.php – PHP script that will display a list box
  • listajax.js – JavaScript file that creates XMLHttpRequest object to send request to the server asynchronously. The options of the list box selected by the user are passed to this JavaScript file
  • showlistdata.php – Server side PHP script to display the response i.e. the options of the list box selected by the user

Coding for “Sending List box option to the server asynchronously”

The coding of listajax.php is as under :

listajax.php

<html>

<head>

<script type=”text/JavaScript” src=”listajax.js”></script>

</head>

<body>

Choose one or more category: <br>

<select multiple=”multiple” size=”4″ onblur=’itemdisplay()’ >

<option value=”Camera” selected>Camera</option>

<option value=”Mobile”>Mobile</option>

<option value=”Book”>Book</option>

<option value=”Computer”>Computer</option>

<option value=”Washing Machine”>Washing Machine</option>

<option value=”Refrigerator”>Refrigerator</option>

</select><br><br>

<div id=”info”></div></body>

</html>

Above program creates a list box with name “Category” with six items : Camera, Mobile and Book, Computer, Washing Machine and refrigerator displayed in it. The multiselect feature of the listbox is set with the help of “multiple” attribute. So, user can select more than one item from the list box (by pressing Ctrl key). After selecting the item(s), the moment user presses tab key or clicks anywhere else on the web page i.e. when the focus of the listbox is lost, a method : itemdisplay() is invoked. Beside this,  a <div> element is defined with id : “info”  for displaying the server response

The coding of the JavaScript file, listajax.js is as under :

listajax.js

1.       function makeRequestObject(){

2.       var xmlhttp=false;

3.       try {

4.       xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’);

5.       } catch (e) {

6.       try {

7.       xmlhttp = new

8.       ActiveXObject(‘Microsoft.XMLHTTP’);

9.       } catch (E) {

10.    xmlhttp = false;

11.    }

12.    }

13.    if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {

14.    xmlhttp = new XMLHttpRequest();

15.    }

16.    return xmlhttp;

17.    }

18.    function itemdisplay()

19.    {

20.    var xmlhttp=makeRequestObject();

21.    optionsArray=document.getElementById(‘Category’).options;

22.    var selectedArray = new Array();

23.    var x=0;

24.    for(var i=0; i< optionsArray.length; i++)

25.    {

26.    if(optionsArray[i].selected)

27.    {

28.    selectedArray[x]=optionsArray[i].value;

29.    x++;

30.    }

31.    }

32.    var cat=””;

33.    for(var i=0;i<selectedArray.length;i++)

34.    {

35.    if( i!=selectedArray.length -1) {

36.    cat +=selectedArray[i]+”,”;

37.    }

38.    else

39.    {

40.    cat+=selectedArray[i];

41.    }

42.    }

43.    xmlhttp.open(‘GET’, ‘showlistdata.php?&Category=’+cat, true);

44.    xmlhttp.onreadystatechange=function() {

45.    if (xmlhttp.readyState==4 && xmlhttp.status == 200) {

46.    var content = xmlhttp.responseText;

47.    if( content ){

48.    document.getElementById(‘info’).innerHTML = content;

49.    }

50.    }

51.    }

52.    xmlhttp.send(null)

53.    }

Explanation of the above program

Statements from 1-17 are making an XMLHttpRequest object.

21.       optionsArray=document.getElementById(‘Category’).options;

The element in the web page with name : “Category” (our listbox) is searched and all the items available in it are assigned to an array : optionsArray.

22.       var selectedArray = new Array();

23.       var x=0;

24.       for(var i=0; i< optionsArray.length; i++)

25.       {

26.       if(optionsArray[i].selected)

27.       {

28.       selectedArray[x]=optionsArray[i].value;

29.       x++;

30.       }

31.       }

With the help of a loop, all the elements in the optionsArray are checked one by one and all the items selected by the user are stored in a separate array : selectedArray.

32.       var cat=””;

33.       for(var i=0;i<selectedArray.length;i++)

34.       {

35.       if( i!=selectedArray.length -1) {

36.       cat +=selectedArray[i]+”,”;

37.       }

38.       else

39.       {

40.       cat+=selectedArray[i];

41.       }

42.       }

All the items stored in array : selectedArray (containing only the list of items selected by the user ) are retrieved and stored in a variable cat (after separating them by commas except the last one)

43.       xmlhttp.open(‘GET’, ‘showlistdata.php?&Category=’+cat, true);

44.       xmlhttp.onreadystatechange=function() {

45.       if (xmlhttp.readyState==4 && xmlhttp.status == 200) {

46.       var content = xmlhttp.responseText;

47.       if( content ){

48.       document.getElementById(‘info’).innerHTML = content;

49.       }

50.       }

51.       }

XMLHttpRequest request is made to the  server (by GET method) for the file showlistdata.php, sending all the item(s) selected by the user (stored in variable cat) to it. The selected item list sent to the requested file will be retrieved in showlistdata.php file using $_GET array.

The state and the response to asynchronous request is checked. If the value of readyState property becomes 4 (meaning the request is complete) and the value of the status of the HTTP Request is 200 (which means there is no error), the response is then retrieved from the response stream and is assigned to variable: content which is then applied to the innerHTML property (property  used to display results) of the element with id : “info” to display all the items that are selected by the user in the list box

Again the response generated by the server is based on the execution of the file : showlistdata.php. Lets analyze what it returns

showlistdata.php

<?php

echo “The categories of items selected are : ” . $_GET[‘Category’] ;

?>

Above file returns the text : “The categories of items selected are “ and the category name(s) selected by the user. The categories selected by the user are passed to this file while making the XMLHttpRequest for the file by following command :

43.  xmlhttp.open(‘GET’, ‘showlistdata.php?&Category=’+cat, true);

Output of “Sending List box option to the server asynchronously”

On executing the file, listajax.php we get a list box with several options as shown in below given figure :

Selecting various items by pressing tab key.

We can select as many category of items as we want followed by pressing tab key. All the categories selected are displayed separated by commas as shown in below given figure.

Selected items are displayed

For more information, refer my book: “Developing Web Applications in PHP and AJAX” available at: http://www.amazon.com/Developing-Web-Applications-PHP-AJAX/dp/0070707103/ref=ntt_at_ep_dpt_4

Here are few  links of my published articles :

Iphone Application to Read And Set Slider’s Value

Validating Date Through Jquery

How to Validate an Email Address Through Jquery

Validating select element in jQuery

Selecting Multiple options in Select element using jQuery

Mobile Web Development using jQTouch:Session Management