AJAX Notes PDF
Document Details
Uploaded by AttentivePink
Tags
Summary
These notes provide a summary overview of AJAX (Asynchronous JavaScript and XML), a technique in web development for interactive and dynamic web applications. It covers the purpose of AJAX, its properties, and use cases. The notes also include a brief discussion of the concept of AJAX and its implementation, security, and comparison with traditional web applications.
Full Transcript
Lecture 16: Ajax Notes ● ChatGPT ○ AJAX, which stands for Asynchronous JavaScript and XML, is a technique used in web development to create interactive and dynamic web applications. ○ AJAX is not a programming language or a tool, but a concept in web development that involves the use of several exis...
Lecture 16: Ajax Notes ● ChatGPT ○ AJAX, which stands for Asynchronous JavaScript and XML, is a technique used in web development to create interactive and dynamic web applications. ○ AJAX is not a programming language or a tool, but a concept in web development that involves the use of several existing technologies together, including HTML/CSS, JavaScript, and XML. It allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. ○ AJAX allows web applications to send and retrieve data from a server asynchronously, without interfering with the display and behavior of the existing page. ○ ○ Purpose of AJAX: ■ Improve User Experience: AJAX enhances the user experience by updating web pages seamlessly without the need to reload the entire page. ■ Reduce Server Load and Bandwidth: Since only parts of a web page are updated, there is less data traffic between the client and the server, which reduces server load and bandwidth usage. ■ Increase Web Application Speed: AJAX can make web applications feel faster and more responsive to user actions since less data is processed and transferred. ■ Real-time Data Update: AJAX allows for real-time data updates on web pages, which is crucial for applications like chat boxes, live feeds, and real-time data visualization. Properties of AJAX: ■ Asynchronous Requests: AJAX allows the browser to send and receive data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. ■ Use of XMLHttpRequest Object: AJAX typically uses the XMLHttpRequest object to request data from a server. ■ Support for Various Data Formats: While it originally stood for Asynchronous JavaScript and XML, AJAX can work with other data formats including JSON, HTML, and plain text. ■ JavaScript and DOM Manipulation: AJAX relies heavily on JavaScript to dynamically display and interact with the information fetched from the server. The DOM (Document Object Model) can be updated in response to user interactions without page reloads. ■ Compatibility with Modern Web Technologies: AJAX can be used in conjunction with other web technologies like PHP, ASP.NET, and APIs to fetch data. ■ ■ ● ● ● ● ● ● ● ● ● ● Cross-Browser Support: Modern browsers support AJAX, though the implementation details may vary. Security: As with any client-server communication, AJAX must be implemented with security considerations in mind to protect data integrity and prevent unauthorized access. ■ MS Windows will be reduced to a poorly debugged set of device drivers running under Netscape Navigator, with desktop-style applications running inside the browser". This did not happen until 10 years later (true/false?) ○ Chromebook was released 2012 Ajax (Asynchronous Javascript + XML) is several technologies in one ○ CSS, XHTML, DOM, XMLHTTPRequest, XML/JSON, Javascript Invented by Jesse James garrett in 2005 In summary, AJAX is a technique that allows web developers to build more dynamic and responsive web applications by making asynchronous requests to servers and updating web page content without requiring a full page reload. XMLHTTPRequest object is the main element ajax programming Microsoft IE 5 was the first Ajax-enabled browser Google Maps implements Ajax behind the scenes Characteristics of Ajax App ○ They are apps/applications not web sites(sites=multiple pages) ○ Allow for smooth, continuous interaction…never see an hourglass ○ “Live” content…data is effective immediate ○ Visual effects and animations/dynamic icons…google maps little guy animation ○ New widgets(selectors, buttons, tabs, lists) ○ Key shortcuts Comparing traditional vs Ajax websites ○ Traditional ■ Interface construction is mainly responsibility of the server ■ User interaction is via form submission ■ Entire page is required for each interaction(bandwith) ■ Application is unavailable while an interaction is processing(browser is blocked…need to wait until server returns what it needs to return) ○ Ajax ■ interface is manipulated by client-side JavaScript manipulations of the Document Object Model(DOM ■ Interaction via http requests occur behind the scenes ■ Communication can be restricted to data only ■ Application is always responsive How to recognize ajax ○ Iframe, ○ jQuery Ajax functions (as jQuery.ajax()) ○ • fetch() ● ● ● ● ● ○ Javascript code that invokes:– XMLHttpRequest Ajax introduces an intermediary — an Ajax engine — between the user and the server. ○ Ajax Engine handles: simple data validation, editing data in memory, and navigation Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine — written in JavaScript and usually stored in a hidden frame. In a traditional classic web app model, the browser is locked up when server is processing XMLHttpRequest Object ○ When readyState (property) is complete and status(property) is 200 ok ○ Then you can get the data vis responseXML and responseText ■ JSON is responseText but we need to eval(responseText) ● Eval is not good so we need to do json.parse(responseText) ○ Red is what you need and important..yellow is discarded ■ ■ ■ ● ● ● In that if statement Security Issues ○ When the XMLHttpRequest object operates within a browser, it adopts the same-domain security policies of typical JavaScript activity (sharing the same "sandbox," as it were). ○ First, on most browsers supporting this functionality, the page that bears scripts accessing the object needs to be retrieved via http: protocol, meaning that you won't be able to test the pages from a local hard disk (file: protocol) without some extra security issues cropping up, especially in Mozilla and IE on Windows. ○ Second, the domain of the URL request destination must be the same as the one that serves up the page containing the script. This means, unfortunately, that client-side scripts cannot fetch web service data from other sources and blend that data into a page. Everything must come from the same domain. Alternative: Fetch api ○ Provides CORS ○ You can use fetch easily for REST calls (put, get, post, delete) ○ Is now included in all the browsers CORS was created bc ○ ○ The browser automatically issues the origin header to the domain you are trying to go to…but doesnt mean success just yet…if server doesnt allow the CORs request (doesnt have Access-Control-Allow-Origin), the browser will deliver an error…you will get a false return!! XHR fails…not all services supports CORs CHATGPT: you can use both XMLHttpRequest and the Fetch API for Cross-Origin Resource Sharing (CORS). CORS is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated. 1: XMLHttpRequest and CORS: To make a cross-origin request using XMLHttpRequest, you don't need to do anything special. The browser automatically handles the CORS protocol. When you make a request to a different domain using XMLHttpRequest, the browser adds an Origin header to the request. The server at this other domain can then decide whether to allow or deny the request based on this Origin. If the server allows the request, it will respond with appropriate CORS headers (Access-Control-Allow-Origin) indicating which origins are permitted. 2: Fetch API and CORS: Similar to XMLHttpRequest, the Fetch API also supports CORS and is handled in much the same way. When using the Fetch API to make a request to a different origin, the browser also adds the Origin header, and the server responds with CORS headers if it permits the request. The Fetch API provides a more modern, promise-based approach to making asynchronous requests and is generally preferred over XMLHttpRequest for new development. It's important to note that CORS is enforced by the web browser. If a server doesn't include the appropriate CORS headers in its response, the browser will block the response from being accessed by your JavaScript code. This is a security measure to prevent malicious websites from reading sensitive data from other sites. In summary, both XMLHttpRequest and Fetch API can be used for making cross-origin requests, and the handling of CORS is primarily the responsibility of the server to which the request is made. Lecture 17: Responsive Website Design Notes ● The Need - Mobile Growth ○ Requires the design team to focus on the most important content, data, and functions. ○ There is no space in a 320 by 480-pixel screen (the original 2007 iPhone) for extraneous, unnecessary elements ○ 70% of users are on mobile devices ○ Mobile Devices Offer: ■ Use of geo-location to optimize the experience. ■ Require Switch layouts depending on the way they're held. ■ Need to support rich, multi-touch interfaces ● input devices that recognize two or more simultaneous touches ○ e.g., two finger tap, two finger scroll, pinch, zoom ● some devices also recognize differences in pressure and temperature (i.e., Apple Watch) ○ Design for the Mobile Web: ■ Create an alternative site…. .mobi site ● 2005 they approved .mobi ● <.01 you can buy a .mobi domain but itll cost you nothing nc no one will be on there ■ Using subdomains… mobile.mycompany.com ■ SELECTED METHOD: Use responsive design techniques ..Configure your current website for mobile display using Responsive Web Design (RWD) techniques ○ ● ● ● Reason for not using mobile.mycompany.com websites: ■ Redirects can hinder/annoy search engines ■ 2. Redirects take lots of time ■ 3. If you offer a mobile.website for iPhone, what about for iPad, ■ Android, etc. ■ 4. Sharing a mobile.website will not work for people on laptops, as they ■ will end up with a site designed for a small screen ■ 5. Philosophical: every web resource should live at one URL! What is Responsive Web Design ○ RWD: ■ concept of developing a website in a way that allows the layout to automatically adjust according to the user’s screen resolution (called its viewport). ■ The viewport meta tag lets you set the width and initial scale of the viewport. ■ For example ● <meta name=“viewport” content=“width=590”> ■ The term "Responsive Web Design" was coined by Ethan Marcotte in an article on May 25, 2010. ○ How to Design Responsively ○ A site designed with RWD adapts the layout to the viewing environment by using ■ 1. fluid, proportion-based grids, ● No pixel based… everything is by percentages ■ 2. flexible/scalable images, and ■ 3. CSS3 media queries (you provide different CSS based upon the viewport size). ○ Major Technology Features ○ – media queries ■ A media query consists of a media type (screen) and the actual query enclosed within parentheses, containing a particular media feature ■ ■ ■ @media only screen and (min-width: 601px) and (max-width: 1024px) { ■ ● /* Styles for tablets */} @media only screen and (min-width: 1025px) { ● /* Styles for laptops/desktops */} ■ ■ ○ (max-devicewidth) to inspect, followed by the target value (480px). The query can be zero or more expressions that check for the conditions of particular media features Example: @media (min-width:500px) { … } @media only screen and (max-width: 600px) { ● /* Styles for mobile phones */} • Many older browsers do not support media queries; ● • css3-mediaqueries.js is not recommended library to use ■ Hiding Content on Smaller Screens ● advisable to hide content on the mobile device that would otherwise be visible on the desktop ○ – this is done so users with small screens can avoid long scrolls ○ – the usual way to handle this is to provide a link to "additional content" ● Display: none [1] vs visibility:hidden [2] ○ [1] takes it out completely as if it doesnt exist….it is better [2] still keeps the white space and shows something was there…. Display:none is better – fluid grids ■ Creating Fluid Grids ● In “adaptive grids”, we define pixel-based dimensions. ○ Hence, we have to adjust the widths and heights manually for certain device viewports. ○ Based on pixels ● • In “fluid grids” we define relative-based dimensions. ○ – Since fluid grids flow naturally within the dimensions of its parent container, limited adjustments will be needed for various screen sizes and devices. ○ Based on percentages ○ ● ● So, whenever the device or screen size is changed, elements will adjust their widths and heights by the specified proportions to its parent container. ○ ● Convert pixel to percentage…child pixel/parent pixel or target/context ○ – scalable images ■ To avoid having an image deformed due to the screen size one should avoid specific definitions of width and height and instead use CSS’s max-width property setting it to 100%: ● Img{max-width: 100%} If have xl.css, medium.css, small.css files what is different/same ○ IDs and Class name would be common ○ What changes is whats in the curly brackets… ○ Change the content in each ID and each class Bootstrap ○ Bootstrap is a powerful front-end framework for faster and easier responsive web development ○ • Bootstrap responsive features make your web pages to appear more appropriately on different devices and screen resolutions without any change in markup ○ Bootstrap 3 provides 4-grid tier : xs, sm, md, lg ○ BS 4 - 5 grid tier ○ BS 5 - 6grid tier : (xs, sm, md, lg, xl, xxl) Lecture 18: JavaScript Frameworks Notes ● CHATGPT notes ○ JavaScript Runtime: Node.js is not a programming language or a framework; it's a runtime environment that allows you to run JavaScript on the server side. ○ ○ ○ ○ ○ ○ ○ ○ ○ ● Built on V8 Engine: Node.js is built on Chrome's V8 JavaScript engine, which compiles JavaScript directly to native machine code, allowing for efficient performance. Event-Driven and Asynchronous: Node.js operates on a single-threaded, non-blocking, event-driven architecture, making it efficient for handling concurrent requests without creating multiple threads. NPM (Node Package Manager): Node.js comes with a package manager called NPM, which has a vast repository of libraries and tools. This makes it easy to import and use third-party modules in your Node.js applications. Full-Stack JavaScript: With Node.js, developers can write both the client and server parts of a web application in JavaScript. This is a significant advantage for those who want to specialize in JavaScript. Built for Scalability: Its event-driven architecture makes Node.js a good fit for building scalable network applications, particularly those requiring a lot of concurrent connections (like chat apps or real-time tracking systems). Cross-Platform: Node.js is cross-platform, meaning it can run on various operating systems like Windows, Linux, Unix, Mac OS X, etc. Use Cases: It's widely used for developing web applications, especially backend services like APIs, but it's also suitable for building real-time applications, IoT applications, streaming applications, and more. Performance: While Node.js is known for its high performance in handling asynchronous operations, it might not be the best choice for CPU-intensive operations. Microservices: Node.js is often used in microservices architectures due to its lightweight nature and quick startup time. ○ NodeJs ○ The main purpose of nodejs is building web servers using javascript ○ Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. ○ Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. ○ Node.js allows the creation of Web servers and networking tools using JavaScript and a collection of "modules" that handle various core functionality. ○ Modules handle file system I/O, networking (DNS, HTTP, TCP, TLS/SSL, or UDP), binary data (buffers), cryptography functions, data streams and other core functions. ○ Basic Functionality ■ HTTP ● • To use the HTTP server and client one must require('http'). ■ ■ ● ● File System ● File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require('fs'). All the methods have asynchronous and synchronous forms.. ● Buffer ● The Buffer class is a global within Node.js, making it unlikely that one would need to ever use require('buffer'). Angular ○ AngularJS is a complete JavaScript-based open-source front-end web application framework. ○ It is mainly maintained by Google and some community of individuals. ○ It provides a framework for client-side model–view–controller (MVC) and model– view–viewmodel (MVVM) architectures. ○ AngularJS is the frontend part of the MEAN stack, consisting of MongoDB database, Express.js web application server framework, Angular.js itself, and Node.js runtime environment. ○ Why Angular.js? ■ HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. ■ root problem is that HTML was not designed for dynamic views. ■ Single Page Applications (SPAs): Angular was developed with the vision of creating more efficient and smoother experiences for SPAs, where a single HTML page is dynamically updated as the user interacts with the app, rather than loading new pages from the server. ○ Basic Functionality ■ Control of the App ● Data Binding: Data-binding is an automatic way of updating the view whenever the model changes, as well as updating the ○ ○ model whenever the view changes. This is awesome because it eliminates DOM manipulation from the list of things you have to worry about. ● Controller: Controllers are the behavior behind the DOM elements. ■ Wire up a Backend ● Form validation: Client-side form validation is an important part of great user experience. AngularJS lets you declare the validation rules of the form without having to write JavaScript code. ● Server Communication: AngularJS provides built-in services on top of XHR (XMLHttpRequest) as well as various other backends using third party libraries. ■ Create Components ● Directives: Directives is a unique and powerful feature available only in Angular. Directives let you invent new HTML syntax, specific to your application ● Reusable Components: We use directives to create reusable components. A component allows you to hide complex DOM structure, CSS, and behavior. This lets you focus either on what the application does or how the application looks separately. ● Localization: Angular's locale aware filters and stemming directives give you building blocks to make your application available in all locales. Goals of AngularJS: ■ – It decouples DOM manipulation from application logic ■ It decouple the client side of an application from the server side ■ Provides structure for building an application: ● Designing the UI ● Writing the business logic ● Testing ■ Angular JS framework adapts and extends traditional HTML. ■ It supports dynamic content through two-way data-binding. ■ Two-way data-binding allows for the automatic synchronization of models and views. Angular 2+ ■ Angular 2+ stands for the Angular 2 and later, including Angular 2,4,5,6,7 and 8. ■ Angular 2+ is a ground-up rewrite. ○ ■ Typescript ■ Open-source programming language developed and maintained by Microsoft ■ Syntactical superset of JavaScrip Here's how Angular uses AJAX: HttpClient Module: Angular's HttpClient is a modernized version of the older $http service from AngularJS. It provides a more powerful, flexible API for making HTTP requests. Asynchronous Operations: Angular uses RxJS (Reactive Extensions for JavaScript) observables to handle asynchronous operations. When you make an HTTP request with HttpClient, it returns an observable. This observable will emit the data from the response when it arrives, allowing the application to handle it asynchronously. ○ Lecture 19: jQuery Notes ● What is JQuery? ○ A framework for client-side JavaScript. ■ An alternative to common javascript tasks ○ It simplifies ■ – HTML document traversing ■ – Event Handling ■ – Animating ■ – AJAX interactions ● What is available with JQuery? ○ Cross browser support and detection ○ Ajax functions ○ CSS Functions ○ DOM Manipulation ○ DOM Transversal ● ● ● ○ Attribute manipulation ○ Event detection and handling ○ JS animation Instead of: var myButton = document.getElementById("myButton"); ○ JQuery it is: $("#myButton"); Selecting all form elements of a certain type: $(‘:text’) It selects all text fields. Use with :input ( all form elements), :password, :radio, :checkbox, :submit, :image, :reset, :button, :file, :hidden ● ○ ○ ○ ○ ○ 1: $( "input[name*='man']" ).val( "has man in it!" ); 2:$( "input[name~='man']" ).val( "mr. man is in it!" ); …only one has exactly “man” 3: $( "input[name$='letter']" ).val( "a letter" );..ends with letter 4:exact equal jQuery( "[attribute^='value']" )....$( "input[name^='news']" ).val( "news here!" ); ■ Starts with news..Finds all inputs with an attribute name that starts with 'news' and puts text in them. ■ ● ● https://api.jquery.com/category/selectors/ ● ● ● Is JQuery Worth it? ○ FInal Notes ○ Allow you to write Javascript differently…Write less, do more ○ Remember: jQuery is just JavaScript ■ What you can do with jQuery, you can always do without jQuery but with more code.