+ All Categories
Home > Documents > jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting...

jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting...

Date post: 22-Mar-2018
Category:
Upload: leanh
View: 218 times
Download: 1 times
Share this document with a friend
23
jQuery & APEX Primer Welcome 3 4 About Me @sspendol [email protected]
Transcript
Page 1: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

jQuery & APEX Primer

Welcome

3 4

About Me

@sspendol

[email protected]

Page 2: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

About Sumner Technologies• Originally Established 2005

• Relaunched in 2015– Focused exclusively on Oracle APEX solutions

• Provide wide range of APEX related Services– Architecture Design & Reviews

– Security Reviews

– Health Checks

– Education • On-site, On-line, On-Demand

• Custom & Mentoring

– Oracle Database Cloud Consulting

– Curators of APEX-SERT

5

Agenda• Intro to jQuery

• jQuery in APEX

• Summary

6

Intro to jQuery

7

jQuery• From jquery.com:

8

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax

much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of

versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

Page 3: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

What does that mean?• “….fast, small, and feature-rich JavaScript library”

– Write a lot less code to do the same thing

– Not worry about cross-browser issues

– Be able to do things that you could not write on your own

• “…HTML document traversal and manipulation, event handling, animation, and Ajax much simpler”

– Select a page component and change its properties

– Add animation effects for transitions

– Communicate with a database asynchronously with ease

9

jQuery Simplification• Without jQuery:

– document.getElementById("example");

• With jQuery:– $("#example");

10

Using jQuery• jQuery is open source, so there is no license fee to use it

– Released under the MIT license

• Which means you can do pretty much anything with it, as long as you leave the copyright header intact

• APEX includes jQuery, so there is no reason to download and host it again, as it’s already there• Otherwise, simply download and reference it from your HTML files

• Or refer to it from a CDN, such as jQuery or Google

11

Using jQuery• Bookmark and make use of the following sites:

– jQuery API Documentation– http://api.jquery.com

– You will refer to it quite a bit as you learn and use jQuery

– jQuery Learning Center– https://learn.jquery.com

– Step-by-Step exercises that help explain how to us jQuery

12

Page 4: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Simple Example• Consider the following HTML file, demo.html:

13

<!DOCTYPE html> <html> <head> <title>jQuery Demo</title> <script src="jquery-2.2.0.min.js"></script> <script src="my.js"></script> </head> <body> <p class="intro">Hello, World</p> </body> </html>

jQuery

Custom

Results• When we run demo.html, we see the following:

14

1) Simple HTML Example• Open demo.html in your browser & inspect the page

– Notice the three files:

15

Ready Method• You will want to be sure that the entire page has loaded

before running jQuery

– This ensures that all DOM elements are present

• There is a built-in function for this:

• Which can also be called like this:

16

$(document).ready(function() { // your code here });

$(function() { // your code here });

Page 5: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Results• If we add a simple function to my.js

• When we reload our page, we’ll get the following:

17

$(function() { alert('hello'); });

2) Add a Function to my.js• Add a simple function to my.js• Reload your page

18

Selectors• In jQuery, selectors allow developers to select and

manipulate HTML elements

– Used to "find" HTML elements based on:

• id

• classes

• types

• attributes

• values of attributes

• All selectors in jQuery start with the dollar sign and parentheses: $()

19

Element Selector• Selects based on element name– Will be applied to all elements that match

• Adding the following function to my.js will look for any and all <p> elements in the HTML and change the background to orange– $("p").css("background", "orange");

20

<body> <p class="intro">Hello, World</p> </body>

Page 6: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

3) Selectors• Change the function in my.js so that it changes any <p>

element to have an orange background

21

Element Selector• An element selector will select all instances of an element

– So if we have three <p> elements, all of them will be selected

22

<body> <p class="foo">Hello, World</p> <p class="fee">Goodbye, World</p> <p class="faa">So Long!</p> </body>

4) More Selectors• Change the source of demo.html so that it has three

<p> elements and reload the page

23

id Selector• Selects based on id– Will be applied to only the id that matches

– $("#id"), where id is the actual id an an element

– For example:

– $("#1").css("background", "orange");

• An id should be unique within a page

– But there is no mechanism that guarantees this

– Best practice is to ensure that it remains unique

24

Page 7: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

5) Using an ID Selector• Change the source of both demo.html and my.js so

that it uses a more precise selector based on an ID, not an element– Alter my.js to select the other ID’s in the HTML

25

Class Selector• Another way to select elements is to use their class– Class is typically associated with CSS and used to change the look

& feel of elements

– But can also be associated with an element or group of elements for the purpose of interacting with them

– Or both

– Quite flexible, as it can be used for:

• A single class

• Multiple classes

• Classes only on specific elements

26

6) Using a Class Selector• Change the source of my.js to select elements that have

the class “foo” associated with them

– Alter my.js to select the other classes in the HTML source

27

7) Using a Class Selector• Next, change the source of demo.html and introduce

three <div> elements with the same classes as the three <p> elements

– Refresh the page and notice that all instances of the foo class are orange, regardless of the element type

28

Page 8: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Element and Class Selectors• It is possible to combine an element selector and a class

selector to get a more specific result

• Consider our HTML now:

– There are two elements with the foo class - a <p> and a <div>

– Selecting the foo class will select them both

• Which may not be the desired result

– Use element.class in the select to narrow it down:

– $("p.foo").css("background", "orange");

29

8) Element and Class Selectors• Change the class selector in my.js so that it only selects

<p> elements with the foo class

30

Element Selector Revisited• Not only can you augment element selectors with a class,

but you can use other selectors– $("p:first")

– $("p:last") – $("p:empty")

– Many others exist as well; see the API Documentation

31

9) Element Selectors• Change the source of my.js so that it selects the first <p>

element and the last <div> element and highlights them in orange

32

Page 9: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Chaining• jQuery can do more than thing at a time

– Called “chaining”

• Allows multiple methods to be performed on the same element

– For example, we can select any <p> element that does not have any text and apply two properties to it:

• Add text to the element

• Change the background to orange

33

$("p:empty") .text( "Was empty!" ) .css( "background", "orange" );

10) Chaining• Alter both the demo.html and my.js files so that any

empty <p> element has its background color changed to orange and contains some text

34

Events• Changing properties when the page load is not all jQuery

can do

– It can listen for events - such as hover, click, scroll, etc. - and then do something when the event occurs

– See the jQuery API Documentation for a list of methods & handlers and how to invoke them

35

Events: click• Rather than automatically change colors, we can change our

jQuery ready function to listen for when the user clicks on a specific selector

– In this case, any <p> element

• When the user clicks, we can then call a function

36

$("p").click( function(){ $(this).css("background","orange") } );

Page 10: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Remember this?• In JavaScript, this is used to refer to the current object

• jQuery makes use of this, too

– $(this).property

37

Events with More Specific Selectors• We can apply more specific selectors to our jQuery code

to only change the color of a <p> element if the class is foo:

38

$("p.foo").click( function(){ $(this).css("background","orange") } );

11) Events: click• Alter both the demo.html and my.js so that as any

<p> element is clicked, the background will change to orange

– Change my.js to only change the color if the class is foo

39

jQuery in APEX

40

Page 11: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

jQuery in APEX• With each release of APEX, more and more

integration with JavaScript has been added

– Since APEX 4.0, there has been a shift towards jQuery– In APEX 5, that shift is mostly complete, as all APEX APIs are

now jQuery-based

• Older ones will still work for the foreseeable future

41

jQuery in APEX• Having said that - it is still recommended to use

Dynamic Actions as much as possible– Upgradable

– Declarative

– Easier to Troubleshoot and Manage

– Can use jQuery calls in conjunction with them

• After all, they use jQuery, too!

42

jQuery APEX APIs

43

Integrating with APEX• The APEX developers went to great lengths to create a set

of JavaScript functions designed specifically for APEX

• Three types of API

– Namespace

– Non-Namespace

– Legacy

• See the APEX API Reference for specifics

– Chapter 29 contains all JavaScript APIs

44

Page 12: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Integrating with APEX• Always refer to the APEX JavaScript libraries before

writing any JavaScript

– It’s likely what you want to do has been done before

– APEX JavaScript libraries will save you tremendous amounts of time and make your code more readable at the same time

45

Namespace APIs

46

Namespace• A Namespace is a way to encapsulate a set of variables

and functions in jQuery

– Give you flexibility to name your functions and variables whatever you want and not step on others with the same name

– Functions and variables will need to be referenced using object literal notation:

• namespace.function or namespace.variable

47 48

Namespace ExampleApp = {};

foo: function() { // ... }, bar: function() { // ... } };

// call a function App.foo(); App.bar();

Page 13: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

49

Embedded Namespace ExampleApp = {};

App.Slider = { // slider code here };

// util functions under a base Utils namespace App.Utils = { foo: function() { // ... }, bar: function() { // ... } };

// call a function App.Utils.foo(); App.Slider();

apex Namespace• APEX has its own jQuery Namespace: apex– Which also have several embedded namespaces

• da

• debug • event • item

• lang • navigation • server

• storage • util • widget

50

51

apex Namespace ReferenceNamespace Description

da Dynamic Actions

debug Debugging

event Event-related Functions

item Item-related Functions

lang Localization-related Functions

navigation Popup & Redirect-related Functions

server Ajax-related Functions

storage Storage-related Functions

util General Utility-related Functions

widget Widget-related Functions

Non-Namespace APIs

52

Page 14: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Non-Namespace APIs• Most of these are older, legacy JavaScript APIs that

are still around for compatibility purposes

– Similar functionality to their Namespace counterparts

• When writing new JavaScript code, it is best to use the Namespace versions of functions– More compatible & manageable

– Less likely to be desupported

– All the benefits of jQuery

53

Non-Namespace APIs• More popular examples include:

– $x, $v, $v2, $s– $x_Hide, $x_Show, $x_Toggle– $x_HideItemRow, $x_ShowItemRow, $x_ToggleItemRow

– $x_Class – $f_CheckAll

54

Legacy JavaScript APIs

55

Legacy JavaScript APIs• Older, no longer supported APIs that should not be

used– Any reference to these APIs should be transferred over to a

Namespace equivalent

– List of functions can be seen in this file:

• /i/libraries/apex/legacy.js

• Can (and should) exclude Legacy Javascript from your application

– Shared Components > User Interfaces > Desktop

• Include Legacy Javascript: No

– Not included with Mobile UI by default

56

Page 15: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

jQuery & APEX Examples

57

jQuery & APEX Examples• When building APEX applications, it’s unlikely you’ll

need jQuery at first– APEX can do most of what most people need declaratively

• But at some point, you’ll outgrow it and need to look to jQuery– Can’t state it enough: use Dynamic Actions and APEX

jQuery APIs– Anything outside of that box will be difficult to maintain and

support over time

58

jQuery & APEX Examples• Some common functionality where jQuery can be used

includes:

– Change Font Size– Delete a Record

– Update Badge Count

59

Change Font Size

60

Page 16: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Change Font Size• One simple thing that jQuery can help with is to change

attributes of page elements• A common example is to allow users to change the

default font size for a site

– Helps with people who have poor vision

• Using some jQuery, we can allow the user to increase or decrease the font size of a specific class

– And store that value as a preference so that it’s always applied for that user

61

APEX Preferences• Preferences in APEX are built-in components that

make it simple to store attribute/value pairs for any user

– Can define on the fly

– Values are mapped to users

– Easy to restore when user logs in

– No additional database objects are required

• Ideal for storing the preferred font size and then restoring it the next time the user logs in

62

Identify the Class• Using Chrome’s developer tools, we can inspect the

items on the page that we want to influence

– Class is a-DetailedContentList-title

63

Region & Item on Global Page• A PL/SQL Region & Page Item are needed on the global

page

– PL/SQL will render an in-line CSS based on the value of the preference

– Item will be used to store the font size

64

htp.prn('<style type="text/css"> .a-DetailedContentList-title { font-size: ' || NVL(APEX_UTIL.GET_PREFERENCE( p_preference => 'FONT_SIZE', p_user => :APP_USER),'14') || 'px; } </style>');

Page 17: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

NavBar Entries• Two NavBar entries - one for increasing and one for

decreasing - need to be created

– URL of # so that they don’t go anywhere

– Class so we can listen for a click

– Needs to added to the User Defined Attributes #2 value

• fontSizeIncrease

• fontSizeDecrease

65

Dynamic Actions• Two DAs need to be created; one to increase the size and

one to decrease it

– Fire on Click

– jQuery Selector• li.fontSizeIncrease

• li.fontSizeDecrease

66

DA: True Actions• JavaScript

• PL/SQL

– Items to submit: P0_FONT_SIZE

67

var fontSize = $(".a-DetailedContentList-title").css("font-size"); var fontSize = Number(fontSize.replace("px","")) + 3; $(".a-DetailedContentList-title").css("font-size", fontSize + "px"); $x("P0_FONT_SIZE").value = fontSize;

APEX_UTIL.SET_PREFERENCE ( p_preference => 'FONT_SIZE', p_value => :P0_FONT_SIZE, p_user => :APP_USER );

Delete a Record

68

Page 18: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Async Delete• Many times, users want to simply delete a row without

having to open the corresponding form

– Quicker and easier

– Can even offer an “are you sure” validation to prevent accidental deletion

• With some simple attribute changes and a dynamic action, this can easily be achieved

69

Async Delete• This solution requires the following components:

– Link Column• Attributes on the column will initiate the delete

– Dynamic Action• Which will call the Ajax Callback via jQuery and refresh the region

– Ajax Callback• PL/SQL Code that performs the delete

70

Async Delete: Column Link• Add a column that contains a Link

– Best to add an additional column to your query that can be used for this

– Primary Key column is likely already used to edit the row

• Set the Link Target Type to URL and the URL to #

71

Async Delete: Column Link• Next, set the Link Text to either the word “Delete” or an

icon of your choice

– <i class="fa fa-trash"></i> will render a trash can

• Set the Link Attributes to the following:

– class="delOrder" id="#DEL#"

72

Page 19: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Async Delete: Column Link• When the link renders, we get the following HTML snippet

for each row (with only the value of id changing):

• Here’s why:

– The class will be used to select this element

• Using a class-based selector allows any row to be clicked

– The id attribute - which is unique - will be used to identify which row was clicked

• And that will be passed to the page item and used in our DELETE Ajax Callback

73

<a href="#" class="delOrder" id="3"> <i class="fa fa-trash”></i> </a>

Async Delete: Dynamic Action• Dynamic Action that fires when a jQuery Selector is

clicked

– jQuery selector is: a.delOrder• Which is derived from: <a href="#" class="delOrder" id="3">

74

Async Delete: Dynamic Action• Multiple true actions:

– Confirm• Simple confirmation message; if user cancels, no further actions occur

– Execute JavaScript Code• Passes the ID to the Ajax Callback, which in turns executes the

PL/SQL

– Refresh• Refreshes the report region

75

apex.server.process• JavaScript API call that calls a PL/SQL on-demand Process

(or Ajax Callback) defined at either the page or application level

– Essentially a wrapper for jQuery.apex function

– Supports all settings plus additional APEX-specific ones

76

Page 20: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

77

apex.server.process

apex.server.process ( "processName", {

x01: "val1", pageItems: "#P1_DEPTNO,#P1_EMPNO"

}, { success: function( pData )

{ ... do something here ... } } );

Ajax Callback Process

Page Items to Set in Session State

Parameters to Pass In

Function to Run if Successful

Object returned from the server

Async Delete: JavaScript• A simple call to apex.server.process, which refers to

the Ajax Callback process delOrder– The id of the triggering element - in this case, the corresponding

trash can icon - is passed to x01, which can be viewed in PL/SQL as apex_application.g_x01

78

apex.server.process("delOrder", { x01: this.triggeringElement.id } );

Async Process: Ajax Callback• An Ajax Callback is a facility in APEX that allows us to

call a database procedure from jQuery without refreshing the page

– Results can be returned and then parsed by jQuery

• Don’t get put off by the name; it’s nothing more than a PL/SQL process that returns data

– Sometimes via htp.prn commands

– Other times by native API calls

79

Async Delete: Ajax Callback• The Ajax Callback is a simple 2-line PL/SQL block

– Line 1 deletes the corresponding row

– Line 2 returns a simple JSON document with 1 value/attribute pair

80

DELETE FROM demo_orders WHERE order_id = apex_application.g_x01; htp.prn('{ "result" : "OK" }');

Page 21: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Update Badge Count

81

Badges• With the advent of the smart phone, a new UI control has

become very popular: the badge

• This popularity has made its way to desktop applications as well

– Thus, users expect it to be available in their APEX applications

82

Badges• To get the badge count to update, we need to change two

things– Ajax Callback needs to return how many rows are left

• This is the easy part

– jQuery needs to take that value and update the badge in the Navigation Menu

• This is the hard part

83

Badges: Ajax Callback• In addition to deleting the corresponding order, we need to

count how many rows are left

– And simply pass that back as part of the JSON document

84

DECLARE l_count NUMBER; BEGIN DELETE FROM demo_orders WHERE order_id = apex_application.g_x01; SELECT COUNT(*) INTO l_count FROM demo_orders; htp.prn('{ "result" : "' || l_count || '" }'); END;

Page 22: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Badges: Ajax Callback• After making the change to the Ajax Callback, we can

see that the number of remaining rows is being passed back in the JSON

85

Badges: Identifying• Now that the correct bit of data is being returned, we have

to capture that & replace the existing badge counter

– There is no easy way to use an id to identify the counter itself

• Thus, we need to find another way– Start with inspecting the HTML

86

Badges: Identifying• The div for Orders has different classes vs. the other items

in the menu

– We can use this combination to select it and then find the inner value of the badge itself

87

Badges: Identifying• Now that we have the div, we can use the find command

in jQuery to find the first instance of the span which contains the badge

88

$("div.a-TreeView-content.is-selected.is-current--top").find('span.a-TreeView-badge')

Page 23: jQuery and APEX Primer - Amazon S3and+APEX+Primer.pdf · –Oracle Database Cloud Consulting –Curators of APEX-SERT 5 Agenda •Intro to jQuery •jQuery in APEX ... jQuery and

Updated JavaScript• Putting it all together, our new JavaScript looks like this:

89

apex.server.process("delOrder", { x01: this.triggeringElement.id }, { success: function(pData) { $("div.a-TreeView-content.is-selected.is-current--top").find('span.a-TreeView-badge').text(pData.result); } } );

Summary

90

Summary• jQuery is a critical part of developing applications in

Oracle APEX

• Despite this, use declarative DAs when possible

– If you need jQuery, it’s best to embed it in a DA

• Code is cheap to create; expensive to maintain– Keep this in mind when choosing if and when and how much

jQuery to use

91 92


Recommended