1 of 31

CSSE280: Forms and AJAX

Get user input and communicate with API

Checkout formsAndAJAX project from your gitter repo

2 of 31

By the end of this unit you should be able to...

  • Explain what a form is, how forms work
  • Explore a variety of form controls
  • Explore HTML5 form controls and form �validation
  • Briefly describe AJAX and its use in �asynchronous communication
  • Use jQuery AJAX wrapper to make AJAX �requests

3 of 31

What is a Form?

A collection of elements that allow you to collect information from visitors to your site

Elements called form controls.

Can use a form

  • to add a simple search box to your site
  • to create more complicated insurance applications

Example forms

Google search box

Registration and login forms for websites you visit

4 of 31

Form controls: text information

There are several types of form controls you can use to collect information from visitors to your site

These form controls allow visitors to your site to enter text information.

Text input: used for single line of text

Password input: like Text input, but with chars masked

Text area: used for longer areas of text that can span multiple lines. e.g., comments, messages

5 of 31

Form controls: making choices

There are several types of form controls you can use to collect information from visitors to your site

These form controls allow visitors to your site to make choices.

Radio buttons: user must select one of multiple options

Checkboxes: user can select and deselect one or more options

Drop-down boxes: user must pick one of multiple options from a list

6 of 31

Form controls: more choices

There are several types of form controls you can use to collect information from visitors to your site

This form control allows visitors to your site to make choices.

Drop-down boxes: user can select one or more options from a list

7 of 31

Form controls: submit form

There are several types of form controls you can use to collect information from visitors to your site

These form controls allow visitors to your site to submit a form.

Submit buttons: to submit data from the form to a web page

Image buttons: like submit buttons, but allow you to use an image

8 of 31

Form controls: file upload

There are several types of form controls you can use to collect information from visitors to your site

This form control allows visitors to your site to upload a file.

File upload: user can upload files to a website

9 of 31

How forms work

A user fills in a form then presses a button to submit the information to the server

Each form control has a name

The name of each form control is sent to the server along with the value the user enters or selects.

Information is sent from the browser to the server using name/value pairs

The server processes the information using a programming language

The server creates a response and sends it back to the browser based on information entered

10 of 31

Form structure

Every form control lives inside a <form> element.

A form can have an action=“URL” attribute

(URL of server to send the form)

A form can have a method=“httpVerb” attribute

(get and post, ways to send form)

Example methods: https://www.w3schools.com/tags/ref_httpmethods.asp

A form can have an id=“someId” attribute to uniquely identify it on the page

11 of 31

Input elements

There are several types of input elements that allow a user to input data into a form.

https://www.tutorialspoint.com/html/html_input_tag.htm provides a list of specific attributes that help differentiate the types of input elements

Relevant attributes for input elements:

Text input: type=“text”, name, maxlength

Password input: type=“password”, name, maxlength, size

Radio button: type=“radio”, name, value, checked

Checkbox: type=“checkbox”, name, value, checked

File input: type=“file”, name

Submit button: type=“submit”, name, value

Image button: type=“image”, name, src,

12 of 31

Text area

Use <textarea> element to create multi-line text input

<textarea name=”comments” cols=”20” rows=”5”> Enter comments ... </textarea>

Avoid cols and rows attributes. Use CSS to control height and width instead

User should delete included text between opening and closing tags, otherwise it will be sent to the server as the value of the text area.

(Also see: textarea placeholder attribute, however, the placeholder attribute of the textarea tag is not supported in Internet Explorer 9 and earlier versions. )

13 of 31

Select form controls:

Use <select> element to create a drop-down list or a multiple select box

The name attribute indicates the name of the form control being sent to the server

<option> elements live inside a <select> element

Each <option> element should have a value attribute.

The selected=“selected” attribute of an <option> element is used to indicate the option that should be selected when the page loads.

Multiple select box takes a size attribute and a multiple=“multiple” attribute.

size indicates the number of options to show at once

Try it: https://www.w3schools.com/tags/tag_select.asp

14 of 31

Button & hidden controls

<button> element was introduced to

  • Allow users more control over how their buttons appear
  • Allow other elements to appear inside the button

You can combine text and images between the opening and closing tags

<input type=“hidden”> represents a hidden form control

Hidden controls are not displayed on the page (can see them in the page code)

They are used to add values to forms that users cannot see

e.g., the page the user was on when they submitted the form

Try it: https://www.w3schools.com/tags/att_input_type_hidden.asp

15 of 31

Label form controls

Each form control should have its own <label> element. This makes the form accessible to vision-impaired users

Can either use label to

  • wrap text description and form input element, OR
  • indicate which form control it is a label for using the for attribute

The value of the for attribute should match the value of the id attribute of the form control that the label is for

Try it: https://www.w3schools.com/tags/tag_label.asp

16 of 31

Grouping form elements

Use <fieldset> element to group related form controls together

Most Browsers will show a <fieldset> element with a line around the edge to show that the contained elements are related

Can use CSS to adjust the appearance of the line

The <legend> element can be placed directly after the opening <fieldset> tag.

The <legend> element contains a caption that helps identify the purpose of the group of form controls

17 of 31

HTML5 input types and form validation

HTML5 introduces new input types

http://html5doctor.com/html5-forms-input-types/ provides

  • a good description, with examples, of these input types
  • Form validation examples -- validates the data entered by the user

18 of 31

TODO

Create a form to use Open movie API to search for information on movies

We will start this in class together the form will look like this (with a narrow window) when done:

19 of 31

AJAX brief overview

Asynchronous JavaScript and XML (AJAX)

  • Not a programming language; a particular way of using JavaScript
  • Fetch data from server in the background
  • Allows dynamic updates of page without making user wait for the whole page to reload
  • Avoids "click-wait-refresh" pattern
  • Concept developed gradually in late 1990's and early 2000's
  • First called "AJAX" in 2005

20 of 31

AJAX

A technique for requesting data from a server and loading it into part of a page without having to refresh the entire page

The data is usually sent in a format called JavaScript Object Notation (JSON) -- http://www.json.org/

Other data formats include HTML, and XML

jQuery makes it easy to create AJAX requests and process the data the server returns

AJAX uses:

Live search (e.g., Google), autocomplete, user-generated data (e.g., Facebook, Twitter, collect the data from servers), online shopping cart

21 of 31

Asynchronous communication with AJAX

User keeps interacting with page while data loads

22 of 31

XMLHttpRequest

  • JavaScript includes an XMLHttpRequest object that can fetch data from a web server
    • Supported in IE5+, Safari, Firefox, Opera, Chrome, etc. (with minor incompatibilities)
  • It can do this asynchronously
    • in the background, transparent to user
  • The contents of the fetched file can be put into current web page using the DOM

sounds great!...

... but it is clunky to use, and has various browser incompatibilities

Better to use the jQuery AJAX wrapper

23 of 31

A typical AJAX request

  1. User clicks, invoking an event handler

  • Handler's code creates an XMLHttpRequest object

  • XMLHttpRequest object requests info from server

  • Server retrieves appropriate data, sends it back

  • XMLHttpRequest fires an event when data arrives
    1. we attach a handler function to this event (callback -- will run later)
    2. callback event handler runs, processes the data, and displays it

24 of 31

jQuery’s Ajax method

$.ajax({

"url": "http://foo.com",

"option" : "value",

"option" : "value",

...

"option" : "value"

});

  • call the $.ajax() method
  • constructor accepts an object literal full of options that dictate the behavior of the Ajax request:
    1. the url to fetch, as a String,
    2. the type of the request, GET or POST
    3. etc...
  • hides icky details of the raw XMLHttpRequest; works well in all browsers

25 of 31

Ajax options

option

description

url

The URL to make a request from

type

whether to use POST or GET

data

an object literal filled with query parameters and their values

dataType

The type of data you are expecting to receive, one of: "text", "html", "json", "xml"

timeout

an amount of time in seconds to wait for the server before giving up

success

event: called when the request finishes successfully

error

event: called when the request fails

complete

event: called when the request finishes successfully or erroneously

26 of 31

jQuery Ajax example

$.ajax({

"url": "foo/bar/mydata.txt",

"type": "GET",

"success": myAjaxSuccessFunction,

"error": ajaxFailure

});

function myAjaxSuccessFunction(data) {

// do something with the data

}

function ajaxFailure(xhr, status, exception) {

console.log(xhr, status, exception);

}

  • attach an event handler function to the request's success and error events

27 of 31

Ajax data parameter

The data passed to your success handler will be in whatever format you specified in the dataType option

  • a dataType of text returns raw text no matter its apparent data type
  • a dataType of html returns raw html text
  • a dataType of xml returns an XML document object
  • a dataType of json returns a JSON object

28 of 31

Handling Ajax errors

$.ajax(

"url": "http://foo.com",

"type": "GET",

"success": functionName,

"error": ajaxFailure

});

...

function ajaxFailure(xhr, status, exception) {

console.log(xhr, status, exception);

}

  • for user's (and developer's) benefit, show an error message if a request fails

29 of 31

Better jQuery Ajax

Rather than specify all of the options in an object literal...

$.ajax({

"url": "http://foo.com",

"type": "GET",

"success": functionName,

"error": ajaxFailure

});

one can pass the URL as the first parameter and the rest as an object literal.

$.ajax("http://foo.com", {

"type": "GET",

"success": functionName,

"error": ajaxFailure

});

Why? It makes it even easier to see what this Ajax request is doing.

30 of 31

Even Better jQuery Ajax

Rather than supply the handlers as fields in the options object...

$.ajax("http://foo.com", {

"type": "GET",

"success": functionName,

"error": ajaxFailure

});

use these event handler function calls done() and fail() instead

$.ajax("http://foo.com", {

"type": "GET"

})

.done(functionName)

.fail(ajaxFailure);

They do the same thing as the success and error options respectively except that they are method calls and let us break up the syntax a little.

31 of 31

TODO

Use jQuery and AJAX to request movie data from the Open movie API

Display movie data on same page as form

Reset form when data is cleared

Will begin in class together

Completing this will be part of your next homework assignment