jQuery and AJAX

Ace your homework & exams now with Quizwiz!

What is the syntax for making an asynchronous GET request from vote.php where option is C?

$.get("/vote.php?option=C", function(data, textStatus, jsXHR) { ... });

What is the syntax for the HTML get/set method callbacks?

has two parameters: - index of current element in a list of elements selected - the original old value - returns the string to use as the new value from the function

SQL vs NoSQL

*SQL* - RDBMS queried using SQL - RDBMS face issues with scalability causing app performance probs - tables are very important *NoSQL* - focus on scalability at the expense of RDBMS benefits - use an application-dependent data structure (eg. tree, graph, key-value) rather than the generic relational structure propagated by RDBMSes - NoSQL operations for an app are faster than RDBMS - tables not very important; vague concept - columns may appear in some rows and not others

What is syntax for document ready event?

$(document).ready(function() { // jQuery methods } OR $(function() { // jQuery methods }

What is the basic jQuery syntax?

$(selector).action() - $ specifies jQuery - selector to specify the HTML elements to select/ query - action is action to be performed on the elements

What is the syntax for page effects like hide and show?

$(selector).funcName(speed, callback) Speed: optional speed param; specifies duration of effect with the following values: slow, normal, fast, numeric Callback: optional callback param; to be executed after original jQuery method completes

Convert the following $.post() request to $.ajax() request: $.post("vote.php", $("#voteForm").serialize());

$.ajax({ url: "vote.php", data: $("#voteForm).serialize(), async: true, type: post });

Define CORS

cross-origin resource sharing - uses new headers in the HTML5 standard implemented in most new browsers

What does the following do? What are the params for the callback function? $("button").click(function(){ $("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){ if(statusTxt=="success") alert("External content loaded successfully!"); if(statusTxt=="error") alert("Error: "+xhr.status+": "+xhr.statusText); }); });

display an alert box after the load() method completes While callback function is optional, params for the callback are not. Params: - responseTxt = contains resulting content if the call succeeded - statusTxt = contains status of the call - xhr = contains XMLHttpRequestObject

What do the following page effects do? hide show toggle slideDown slideUp slideToggle fadeOut fadeIn fadeToggle fadeTo

hide: hide HTML element(s) show: show HTML element(s) toggle: toggle between showing and hiding HTML elements slideDown: slide element down slideUp: slide element up slideToggle: toggle between slide down/ up for an element fadeOut: fade out a visible element fadeIn: fade in a hidden element fadeToggle: toggle between fading in and out fadeTo: fade an element to a given opacity - has a special call syntax compared to previous effects: $(selector).fadeTo(speed, opacity, callback)

What happens when multiple animate() functions are called?

jQuery creates queue of animate() calls, executing them in their order of appearance

What are $.get() and $.post() actually shorthand for?

jQuery().ajax()

What composes the $.get function?

jQuery.get ( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] ) url is a string that holds the location to send the request. data is an optional parameter that is a query string or a Plain Object. success(data,textStatus,jqXHR) is an optional callback function that executes when the response is received. - data holding the body of the response as a string. - textStatus holding the status of the request (i.e., "success"). jqXHR holding a jqXHR object, described shortly. dataType is an optional parameter to hold the type of data expected from the server.

What is the syntax for a POST request?

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

What do the following methods do? load()

load() - retrieve data from a server and load data into the selected element EX: $("div1").load("demo_test.txt");

What does the serialize() function do?

serialize() can be called on any form object to return its current key-value pairing as an & separated string, suitable for use with post().

What does a callback function help with?

to prevent errors in execution - executed after the current effect is finished

What do the following jQuery dimension methods do? width() height() innerWidth() innerHeight() outerWidth() outerHeight() outerWidth(true) outerHeight(true)

width(): sets or returns the width of an element without including padding, border, or margin height(): sets or returns the height of an element without including padding, border, or margin innerWidth(): sets or returns the weight of an element including padding but without including border, or margin innerHeight(): sets or returns the height of an element including padding but without including border, or margin outerWidth(): sets or returns the weight of an element including padding and border but without including margin outerHeight(): sets or returns the height of an element including padding and border but without including margin outerWidth(true): sets or returns the weight of an element including padding, border and margin outerHeight(true): sets or returns the height of an element including padding, border and margin

Describe the Document type of NoSQL

- A document is a central concept in a document-oriented NoSQL DB - Document-oriented database rely on documents that encapsulate and encode data in some standard formats or encodings such as: XML, YAML, JSON - Documents inside a document-oriented database are not required to adhere to a standard schema i.e. documents will not have the same sections, slots, parts, or keys - Document-oriented NoSQL DB approach allows new information to be added to some records without requiring that every other record in the database share the same structure

What features are in the jQuery library?

- HTML/ DOM manipulation - CSS manipulation - HTML event methods - Effects and animations - AJAX - Utilities - Plugins to deal with severed real-world tasks

What are cons of AJAX?

- Pre-HTML5, it breaks browser history engine (back button) - Difficult to bookmark - Dynamic page updates may interfere disruptively with user interactions - most web crawlers don't execute JS code - support issues: Support Issues: browsers not supporting JavaScript or XMLHttpRequest, or simply has these features disabled, will not be able to properly render pages which depend on AJAX - The same origin policy prevents some AJAX techniques from being used across domains - asynchronous callback-style can lead to complex code that is hard to test, debug, and maintain

Pros of using jQuery for AJAX

- different browsers have different syntax for AJAX implementation, so jQuery abstracts away the implementation so differences don't affect the web programmers

What methods do jqXHR objects have? What do they allow us to do?

- done() - fail() - always() allow us to structure code in a more modular way than the inline callback

What does the method noConflict() do?

- releases the hold on the $ shortcut identifier - other scripts can use $ shortcut identifier from that point forward - do NOT use the shortcut! Tho, can pass $ as a parameter to a block of jQuery code where it can be used as the jQuery shortcut

How do jQuery methods support AJAX functionality?

- request text, HTML, XML, or JSON from a remote server using HTTP Get or Post - load the received data into the appropriate HTML element

What does the stop() method do? Does it work on all jQuery effect functions? What is the syntax?

- stops animation or effect before it's completed - works for all jQuery effect functions, even custom $(selector).stop(stopAll, goToEnd); - by default, kills current animation being performed on selected element - stopAll specifies if animation queue also cleared (by default, only active animation is stopped, queue is untouched) - goToEnd param if true means that the current animation be completed immediately

What is the usage for the Document Ready Event?

- used to prevent jQuery code from running before the dom is finished loading - problems can occur if try to manipulate elements not yet created or loaded, so this event allows JS code in the head section while waiting for dom

How do you pass HTTP headers in the following ajax() method? $.ajax({ url: "vote.php", data: $("#voteForm).serialize(), async: true, type: post });

... type: post, headers: {"User-Agent" : "Homebrew JS Vote Engine agent", "Referer" : "http://funwebdev.com" } ... So, the headers are enclosed in a Plain Object

Describe the flow of an AJAX call

1) Browser parses and builds DOM then renders HTML page and runs JS 2) Everything is waiting state until event occurs like user clicks a button. The browser handles the event synchronously in JS 3) JS handles the event asynchronously, requesting a web resource and returns control to the browser 4) while the server processes the request, browser is not stuck waiting in a refresh state 5) JS processes the response 6) JS updates the UI

What do the following HTML CSS methods do? 1) $("div").addClass("important"); 2) $("h1,h2,p").removeClass("blue"); 3) $("h1,h2,p").toggleClass("blue"); 4) $("p").css("background-color"); 5) $("p").css({"background-color":"yellow", "font-size":"200%"});

1) adds class important to all divs 2) removes class blue from h1, h2, and p elements 3) toggles between adding/removing class blue from h1, h2, and p elements 4) returns the value for background-color of p elements 5) sets background-color to yellow and font-size to 200% for all p elements

Compare the following lines of code: 1) var txt1 = "<p>Text.</p>"; 2) var txt2 = $("<p></p>").text("Text"); 3) var txt3 = document.createElement("p"); txt3.innerHTML="Text.";

1) creates text with HTML 2) creates text with jQuery 3) creates text with DOM

Describe what the following does: 1) $(this).hide() 2) $("p").hide() 3) $(".test").hide() 4) $("#test").hide()

1) hides current element 2) hides all <p> elements 3) hides all elements with class="test" 4) hides element with id="test"

What do the following HTML add methods do? 1) $("p").append("Some appended text."); 2) $("p").prepend("Some prepended text."); 3) $("p").after("Some text after."); 4) $("p").before("Some text before.");

1) inserts content at end of the selected elements 2) inserts content at beginning of the selected elements 3) inserts content after the selected p elements 4) inserts content before the p elements

What do the following HTML remove methods do? 1) $("#div1").remove(); 2) $("p").remove(".italic"); 3) $("#div1").empty();

1) removes #div1 element and any children it has - can set parameter to remove specific values 2) removes all <p> elements with class="italic" 3) removes the child elements from the #div1 element

What do the following jQuery selectors select? 1) $("p.intro") 2) $("p:first") 3) $("ul li:first") 4) $("ul li:first-child") 5) $("[href]") 6) $("a[target='_blank']") 7) $(":button") 8) $("tr:even")

1) select all <p> elements with class="intro" 2) select the first <p> element 3) select the first <li> element of the first <ul> element 4) select the first <li> element of every <ul> element 5) select all elements with an href attribute 6) select all <a> elements with a target attribute value equal to "_blank" 7) select all <button> elements and <input> elements of type="button" 8) select all even <tr> elements

Describe the Column type of NoSQL

A column is a central concept in a column-oriented NoSQL DB - A column is a NoSQL object of the lowest level in a keyspace *Note: keyspace is outer most grouping of the data in the data store* - keyspace is a tuple (a key-value pair) consisting of three elements: Unique name: used to reference the column Value: content of the column Timestamp: system timestamp used to determine the valid content

Describe the graph type of NoSQL

A graph-oriented NoSQL database uses graph structures such as nodes, edges, and properties to represent and store data. - Nodes represent entities e.g. people, businesses, accounts, etc. - Properties are information related to nodes - Edges represent relationships between nodes A graph database provides index-free adjacency i.e. every element has a direct pointer to its adjacent elements and hence no index lookups are necessary Graph-oriented NoSQL DB is designed for data whose relations are well represented as a graph i.e. elements interconnected with an undetermined number of relations between them - data could be social relations, public transport links, road maps or network topologies Graph-oriented NoSQL DB provided graph matching and querying language and interface

What is jQuery?

A popular JS library designed to simplify DOM client-side HTML scripting - lightweight, write less to do more

What does AJAX mean?

Asynchronous JavaScript with XML - describes way for web browser to send messages back to server without interrupting browser flow

How can jQuery help traverse the DOM?

Can easily move up (to ancestors), down (to descendants) and sideways (to siblings) in the DOM tree

How do you include/ use jQuery?

Can use 1 of the 2 versions - production or development Include using script tag in the head section - local min.js file reference or reference from CDNs (Content Delivery Network)

How does jQuery interact with DOM?

Via jQuery method - most DOM events have an equivalent jQuery method

What is the document NoSQL key? How retrieve content in document NoSQL? How are documents organized?

Document Key - Each document in the DB has a unique key associated with it Document key can a simple unique string, a URI, or a unique path Document content Retrieval - Document key used to retrieve a document from the database - Typically, the database creates an index of the document keys to speed up retrieval - Documents can also be retrieved based on their content via an API or query language - EX: user can write a query to retrieve all documents containing a certain field or a certain value Organization Documents can be organized as Collections, Tags, Non-visible, Metadata, Directory hierarchies, Buckets

What versions are there for the ajax() method?

First: - takes two parameters: a URL and a Plain Object, containing any of over 30 fields Second: - only one parameter - more commonly used, where the URL is but one of the key-value pairs in the Plain Object

Which is safe: GET request or POST request or both?

GET is a safe method, meaning that they should not change anything, and should only read data POSTs on the other hand are NOT safe

What methods allow jQuery to get HTML content from elements? To get attributes from elements?

Get content: - text() to get text content - html() to get content plus HTML syntax/ markup - val() to get value of form field(s) Get attribute: - attr("name") to get attribute value(s)

What do the following methods do? children("p.1") find("span")

Help traverse DOWN the DOM tree children() - returns all direct children (in this case, of type p with class 1) of the selected element - an optional parameter to filter the search for children find() - returns descendant elements (in this case of type "span") of the selected element, all the way down to the last descendant

What do the following methods do? siblings() next() nextAll() nextUntil() prev() prevAll() prevUntil()

Help traverse SIDE-WAYS on DOM tree siblings() returns all sibling elements of the selected element an optional parameter to filter the search for siblings next() returns the next sibling element of the selected element nextAll() returns all next sibling elements of the selected element nextUntil() returns all next sibling elements between two given arguments prev() returns the previous sibling element of the selected element prevAll() returns all previous sibling elements of the selected element prevUntil() returns all previous sibling elements between two given arguments

What do the following methods do? parent() parents() parentsUntil("div")

Help traverse UP the DOM tree parent() returns the direct parent element of the selected element parents() returns all ancestor elements of the selected element all the way up to the document's root element (<html>) an optional parameter to filter the search for ancestors parentsUntil() returns all ancestor elements between the two given arguments (in this case, get parents until div element encountered)

Describe what the following does: var jqxhr = $.get("/vote.php?option=C"); jqxhr.done(function(data) { console.log(data); }); jqxhr.fail(function(jqXHR) { console.log("Error: " + jqXHR.status); }); jqxhr.always(function(data) { console.log("all done"); });

Makes a get call to vote.php If success, log data Else if fail, log the status Always log "all done"

What are the different types of NoSQL?

NoSQL classification based on data models: - Column: HBase, Accumulo, Cassandra - Document: MarkLogic, MongoDB, Couchbase - Key-value: Dynamo, Riak, Redis, MemcacheDB, Project Voldemort - Graph: Neo4J, OrientDB, Allegro, Virtuoso

Which are preferred: GET requests or POST requests?

POST requests are often preferred to GET requests because one can post an unlimited amount of data, and because they do not generate viewable URLs for each action. GET requests are typically not used when we have forms because of the messy URLs and that limitation on how much data we can transmit. With POST it is possible to transmit files, something which is not possible with GET.

Describe the pros and cons of NoSQL DB

PROS: - Simple - Scalable - Perfect for the Cloud - Object to relational mapping not required - No Entity Joins CONS: - Lack of full ACID support - the use of low-level query languages - the lack of standardized interfaces - huge investments already made in SQL by enterprises

What is the difference between margin and padding?

Padding is between element and the border Margin is between border and the other elements

What is RDBMS?

Relational Database Management System (RDBMS) is a database management system (DBMS) that uses a relational model to represent/store/access data - based on first-order predicate logic - proposed in 1969 by Edgar F. Codd - all data is represented in terms of tuples, grouped into relations provide a declarative method for specifying data and queries - provides a SQL data definition and query language interface - essentially a group of tables (entities) made up of columns and rows (tuples)

Why would the $ shortcut or jQuery cause a conflict? How is the conflict resolved?

Results in conflict if some of the other frameworks also use the $ character as a shortcut Use the noConflict() jQuery method to resolve this conflict

What do all $.get() requests return?

Return a jqXHR object to encapsulate the response from the server - this means the data being referred to in the callback from Listing 15.13 is actually an object with backward compatibility with XMLHttpRequest.

What are jQuery selectors used for?

Selecting elements - use CSS syntax and based on existing CSS selectors tho can have custom selectors as well - can be based on id, classes, types, attributes, values of attributes, or other

When do you want your jQuery functions in a separate .js file? When do you want it all in the same html file?

Separate js file: - website has lots of pages - want easily maintainable jQuery functions - include in script tag in the head All in html file: - easier reading all of the demo code in a presentation

What methods allow jQuery to set HTML content? To set attributes of elements?

Set content: - text("Text") to set text content - html("<p>Text</p>") to set content plus HTML syntax/ markup - val("Duck") to set value of form field(s) Set attribute: - attr("name", "Donald") to set attribute value(s)

Compare the following pieces of code and their effects: $("button").click(function () { $("p").hide(1000); alert("The paragraph is now hidden"); }); $("button").click(function () { $("p").hide("slow", function() { alert("The paragraph is now hidden"); }); });

The first example's alert box will be displayed before the hide effect is completed The second example uses a callback, so the alert box displays once the paragraph is hidden

What do the following methods do? filter() not()

Traverse and find/ select elements that match or don't match criteria filter() - returns elements that match a specified criteria - EX: return all <p> elements with class name "intro": $("p").filter(".intro"); }); not() - returns all elements that do not match a specified criteria - EX: return all <p> elements that do not have class name "intro": $("p").not(".intro");

How can you create custom animations? What is the syntax?

Use animate() method $(selector).animate(cs_params, speed, callback); cs_param: mandatory param that specifies the CSS properties to be animated speed: optional speed param specifies the duration of the effect with the following values: slow, normal, fast, numeric callback: optional callback param to be executed after the original jQuery method completes Animations can absolute, relative to element's current value, or predefined options such as "show" or "hide"

What is the currently accepted way for asynchronous file transmission? What is the path flow for this method?

Use the FormData interface and the File API 1) Submit is clicked 2) JS interrupts the synchronous submission and uses HTML5's FormData to convert the references file into a string 3) Asynchronous $.post() transmits the data to the server and can have a listener execute on completion

What do the following methods do? first() last() eq()

Used to traverse and find/ select a specific element based on its position in a group of elements in the DOM tree first() - returns first element of selected elements - EX: select the first <p> element inside the first <div> element $("div p").first(); last() - returns the last element of the selected elements - EX: select the last <p> element inside the last <div> element: $("div p").last(); eq() - returns an element with a specific index number (starting at 0) of the selected elements - EX: select the second <p> element i.e. at index=1 $("p").eq(1);

What is the pro of doing the FormData technique?

When we consider uploading multiple files, you may want to upload a single file, rather than the entire form every time. To support that pattern, you can access a single file and post it by appending the raw file to a FormData object. The advantage of this technique is that you submit each file to the server asynchronously as the user changes it; and it allows multiple files to be transmitted at once.

Can multiple properties be animated at the same time?

YES - using the animate() method

Since noConflict() gets rid of the $ shortcut, can you make a new shortcut for jQuery?

Yes EX: var jq = $.noConflict(); jq(document).ready(function(){ jq("button").click(function(){ jq("p").text("jQuery is still working!"); }); });

Does jQuery allow chaining of actions/ methods?

Yes - avoids overhead of the selector running multiple times EX: $("#p1").css("color", "red").slideUp(2000).slideDown(2000);

What do the following methods or variables do? abort() getResponseHeader() readyState responseXML or responseText setRequestHeader(name, value) status statusText

abort() stops execution and prevents any callback or handlers from receiving the trigger to execute. getResponseHeader() takes a parameter and gets the current value of that header. readyState is an integer from 1 to 4 representing the state of the request. The values include 1: sending, 3: response being processed, and 4: completed. responseXML and/or responseText the main response to the request. setRequestHeader(name, value) when used before actually instantiating the request allows headers to be changed for the request. status is the HTTP request status codes (200 = ok) statusText is the associated description of the status code.

What should a site do to allow a specific domain to access its content through JS?

add the following header to all its responses Access-Control-Allow-Origin: www.funwebdev.com

What should a site do to allow any domain to access its content through JS?

add the following header to all of its responses. Access-Control-Allow-Origin: *

What does the following do: $("#test1").text(function(i, origText) { return "Old text" + origText + " New text: this is the new text paragraph (index: " + i + ")"; });

changes the element with id #test1 to have text returned from the callback function

What are some example events?

click dblclick mouseenter mouseleave keypress keyup submit change focus blur load resize scroll unload

What was the original workaround to allow the asynchronous posting of files? What was the path flow for this method?

use a hidden <iframe> element to receive the posted files 1) JS creates a hidden iframe on the page 2) Form is submitted into the hidden iframe 3) JS sets up a listener on the iframe's load event and attaches a handler. When the upload is complete, handler is executed

Convert the following GET request to a POST request: var jqxhr = $.get("/vote.php?option=C");

var jqxhr = $.post("/vote.php", "option=C");

How would serialize help get the #voteForm data into a post request to "vote.php"?

var postData = $("#voteForm").serialize(); $.post("vote.php", postData);


Related study sets

A&P 2: Chapter 20 Vessels and Circulation Part 2-a

View Set

UIL Social Studies-People 2021-2022

View Set