27.10.2015 Views

AJAX and PHP

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>AJAX</strong> Suggest <strong>and</strong> Autocomplete<br />

Next, we will talk about the h<strong>and</strong>leKeyUp function. This is the function used for navigation<br />

through the results <strong>and</strong> submission. Since we are interested only in few keys, the others are<br />

ignored. Before getting there we need to make sure the code works on every browser. In order for<br />

this to happen, we need to write a few lines as we can see for ourselves.<br />

In order to know which characters to consider, we need to know the codes of the keys. The event<br />

object received as parameter has a property keyCode that has the code of the pressed key. In the<br />

following table, you can find a list of most of the special keys:<br />

Table 1: Key codes<br />

Key Code Key Code<br />

Backspace 8 Print Screen 44<br />

Tab 9 Delete 46<br />

Enter 13 F1 112<br />

Shift 16 F2 113<br />

Ctrl 17 F3 114<br />

Alt 18 F4 115<br />

Pause/Break 19 F5 116<br />

Caps Lock 20 F6 117<br />

Esc 27 F7 118<br />

Page Up 33 F8 119<br />

Page Down 34 F9 120<br />

End 35 F10 121<br />

Home 36 F11 122<br />

Left Arrow 37 F12 123<br />

Up Arrow 38<br />

Right Arrow 39<br />

Down Arrow 40<br />

On pressing Enter (code 13), the page submits to the php.net help with the specification for the<br />

currently selected suggestion if any is selected. On pressing the up or down arrow keys the<br />

currently selected suggestion moves one position up or down if possible. The current keyword is<br />

also updated with the value of the current selected suggestion. We do not h<strong>and</strong>le any other pressed<br />

keys since they modify the keyword <strong>and</strong> we have already presented the checkForChanges function<br />

that h<strong>and</strong>les this part.<br />

Another problem that arises when having more than ten suggestions available is that we have a<br />

scrollable div region. As we stated before, we want the user to be able to navigate through the<br />

results by using the up <strong>and</strong> down arrow keys. If the user reaches a result that is not currently<br />

186<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!