AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.

Slides:



Advertisements
Similar presentations
JavaScript & jQuery the missing manual Chapter 11
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
AJAX in ASP.NET MVC AJAX, Partial Page Rendering, jQuery AJAX, MVC AJAX Helpers SoftUni Team Technical Trainers Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JQuery Overview Unleash the Power of jQuery SoftUni Team Technical Trainers Software University
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
DOM, jQuery, AJAX, REST Using Kinvey as JS Back-End
Software Technologies
Version Control Systems
Helpers, Data Validation
Databases basics Course Introduction SoftUni Team Databases basics
C# MVC Frameworks – ASP.NET
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
WordPress Introduction
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
JavaScript Applications
Source Control Systems
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Mocking tools for easier unit testing
JavaScript Applications
State Management Cookies, Sessions SoftUni Team State Management
Browser Routing Design Patterns in JS
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Software Technologies
Registration, Login, Thymeleaf
Unit Testing with Mocha
C#/Java Web Development Basics
MVC Architecture. Routing
Creating React Components with JSX and Babel
Front-End Framework for Responsive Web Sites
Entity Framework: Relations
Caching Data in ASP.NET MVC
Modules, Babel, RequireJS, Other JavaScript Module Systems
The Right Way Control Flow
MVC Architecture, Symfony Framework for PHP Web Apps
ASP.NET SignalR SoftUni Team C# MVC Frameworks Technical Trainers
ASP.NET MVC Introduction
JavaScript Fundamentals
Databases Advanced Course Introduction SoftUni Team Databases Advanced
C# Web Development Basics
Creating UI elements with Handlebars
Best practices and architecture
WordPress Plugins Popular WP Plugins: Sliders, Forms, Contacts, SEO, Forum, Photo Gallery, e-Commerce WordPress Plugins SoftUni Team Technical Trainers.
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Course Overview, Trainers, Evaluation
Scheduled Tasks and Web Socket
JavaScript Fundamentals
Train the Trainers Course
Software Quality Assurance
Directives & Forms Capturing User Input SoftUni Team
Version Control Systems
JavaScript Frameworks & AngularJS
First-Class Functions
JavaScript: ExpressJS Overview
Iterators and Generators
HTTP, RESTful Web Services, HTTP and REST Tools: Postman, Fiddler
Presentation transcript:

AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents AJAX Concepts XMLHttpRequest jQuery AJAX $.load $.get() / $.post() $.ajax() AJAX – Examples Accessing Firebase with AJAX

Have a Question? sli.do #JSAPPS

What is AJAX? AJAX == Asynchronous JavaScript And XML Technique for background loading of dynamic content / data Web pages / apps load data from the Web server and render it Two types of AJAX Partial page rendering Load HTML fragment + show it in a <div> JSON service Load JSON object and display it with JavaScript / jQuery

AJAX: Workflow Web Client Web Server Modify the page DOM 1. HTTP request (initial page load) 2. HTTP response (HTML page) Web Client Web Server AJAX request UI Interaction AJAX handler AJAX response (asynchronous) Returns data as JSON / HTML Modify the page DOM

Using the XMLHttpRequest Object Web Client Web Server AJAX request AJAX response Using the XMLHttpRequest Object

XMLHttpRequest – Standard API for AJAX <button onclick="loadRepos()">Load Repos</button> <div id="res"></div> function loadRepos() { let req = new XMLHttpRequest(); req.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) document.getElementById("res").textContent = this.responseText; }; req.open("GET", "https://api.github.com/users/testnakov/repos", true); req.send(); } Check your code here: https://judge.softuni.bg/Contests/357

Simplified AJAX Calls with jQuery jQuery AJAX Simplified AJAX Calls with jQuery

jQuery AJAX jQuery dramatically simplifies how developer make AJAX calls Problem: create a page holding a button Clicking the button should load a html fragment and display it inside a div

Solution: jQuery.load() ajax-load.html <div id="text"> <h1>AJAX jQuery.load()</h1> <button onclick="loadTitle()">Load Title</button> </div> ajax-load.js text.html function loadTitle() { $('#text').load("text.html"); } <h1>Voilla!</h1> <p>I am a text loaded with AJAX request</p> Check your solution here: https://judge.softuni.bg/Contests/357 Submit in the judge the JS function loadTitle()

Handling Errors Scripts can execute AJAX requests Uses a special HTTP header: Access-Control-Allow-Origin Scripts can execute AJAX requests Either to their origin (same-origin policy) Or when the remote server explicitly allows AJAX calls via CORS $(document).ajaxError(function(event, req, settings) { $('#text').text(`Error loading data: ${req.status} (${req.statusText})`); }); function loadTitle() { $('#text').load("http://dir.bg"); } This cross-origin AJAX request will fail due to missing CORS headers

Problem: Load GitHub Repos with AJAX GitHub username: <input type="text" id="username" value="testnakov" /> <button onclick="loadRepos()">Load Repos</button> <ul id="repos"></ul> <script> function loadRepos() { // AJAX call … } </script>

Solution: Load GitHub Repos with AJAX function loadRepos() { $("#repos").empty(); let url = "https://api.github.com/users/" + $("#username").val() + "/repos"; $.ajax({ url, success: displayRepos, error: displayError }); function displayRepos(respos) { … } function displayError(err) { … } }

Solution: Load GitHub Repos with AJAX (2) function displayRepos(respos) { for (let repo of respos) { let link = $('<a>').text(repo.full_name); link.attr('href', repo.html_url); $("#repos").append($('<li>').append(link)); } function displayError(err) { $("#repos").append($("<li>Error</li>")); Check your solution here: https://judge.softuni.bg/Contests/357

Using jQuery to Access REST APIs Examples AJAX – Examples Using jQuery to Access REST APIs

Problem: Phonebook App in Firebase Create a mini phonebook JS front-end app Hold your data in Firebase Disable the authentication to simplify your work Implement "list phones", "add phone", "delete phone"

Solution: Setup a Firebase DB Open https://console.firebase.google.com/ Create a new project Enable public read / write access

Solution: Add Sample Data in Firebase

Solution: Test Your REST Service

Solution: Phonebook in Firebase – HTML <h1>Phonebook</h1> <ul id="phonebook"></ul> <button id="btnLoad">Load</button> <h2>Create Contact</h2> Person: <input type="text" id="person" /> <br> Phone: <input type="text" id="phone" /> <button id="btnCreate">Create</button>

Solution: Phonebook in Firebase – JS Code $(function () { $('#btnLoad').click(loadContacts); $('#btnCreate').click(createContact); let baseServiceUrl = 'https://phonebook-nakov.firebaseio.com/phonebook'; function loadContacts() { … } function displayContacts(contacts) { … } function displayError(err) { … } function createContact() { … } function deleteContact(key) { … } });

Solution: Phonebook in Firebase – JS Code function loadContacts() { $("#phonebook").empty(); $.get(baseServiceUrl + '.json') .then(displayContacts) .catch(displayError); } function displayError(err) { $("#phonebook").append($("<li>Error</li>"));

Solution: Phonebook in Firebase – JS Code function displayContacts(contacts) { for (let key in contacts) { let person = contacts[key]['person']; let phone = contacts[key]['phone']; let li = $("<li>"); li.text(person + ': ' + phone + ' '); $("#phonebook").append(li); li.append($("<button>Delete</button>") .click(deleteContact.bind(this, key))); } Bind the event handler with the current key

Solution: Phonebook in Firebase – JS Code function createContact() { let newContactJSON = JSON.stringify({ person: $('#person').val(), phone: $('#phone').val() }); $.post(baseServiceUrl + '.json', newContactJSON) .then(loadContacts) .catch(displayError); $('#person').val(''); $('#phone').val(''); }

Solution: Phonebook in Firebase – JS Code The correct contact key will come as parameter (due to binding) function deleteContact(key) { let request = { method: 'DELETE', url: baseServiceUrl + '/' + key + '.json' }; $.ajax(request) .then(loadContacts) .catch(displayError); } Check your solution here: https://judge.softuni.bg/Contests/357

Live Exercises in Class (Lab) Practice: jQuery AJAX Live Exercises in Class (Lab)

Summary AJAX sends asynchronous HTTP requests from JS jQuery simplifies how developers use AJAX $.ajax({ url, method: 'GET', success: displayRepos, error: displayError }); function displayRepos(respos) { … } function displayError(err) { … } }

AJAX and jQuery AJAX https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.