Презентация

AJAX and jQuery AJAX - JS Applications - ноември 2016

 

Материали от темата

Съдържание на документа

AJAX and jQuery AJAX

AJAX Concepts, XMLHttpRequest,
jQuery AJAX: $.ajax(), $.get(), $.post()

SoftUni Team

Technical Trainers

Software University

http://softuni.bg

jQuery
AJAX

XMLHttpRequest




Table of Contents

AJAX Concepts

XMLHttpRequest

jQuery AJAX

$.load

$.get() / $.post()

$.ajax()

AJAX – Examples

Accessing Firebase with AJAX

2


3



sli.do
#ajax

Have a Question?


4

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

What is AJAX?


5

AJAX: Workflow



1. HTTP request (initial page load)



2. HTTP response (HTML page)



AJAX request

UI Interaction



Modify the page DOM

AJAX handler



AJAX response (asynchronous)

Returns data as JSON / HTML

Web Client

Web Server




Using the XMLHttpRequest Object

XMLHttpRequest





AJAX request

AJAX response

Web Server

Web Client


7

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


jQuery AJAX

Simplified AJAX Calls with jQuery


9

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 

jQuery AJAX




<div id="text">

  <h1>AJAX jQuery.load()</h1>

  <button onclick="loadTitle()">Load Title</button>

</div>

10

Solution: jQuery.load()

Check your solution here: https://judge.softuni.bg/Contests/357

Submit in the judge the JS function loadTitle()

function loadTitle() {

  $('#text').load("text.html");

}

<h1>Voilla!</h1>

<p>I am a text loaded with AJAX request</p>

ajax-load.html

ajax-load.js

text.html


11

Scripts can execute AJAX requests

Either to their origin (same-origin policy)

Or when the remote server explicitly allows AJAX calls via CORS

Handling Errors

$(document).ajaxError(function(event, req, settings) {

  $('#text').text(`Error loading data: ${req.status} (${req.statusText})`);

});

function loadTitle() {

  $('#text').load("http://dir.bg");

}

Uses a special HTTP header: Access-Control-Allow-Origin

This cross-origin AJAX request will fail due to missing CORS headers


12

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>


13

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) { … }

}


14

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


AJAX – Examples

Using jQuery to Access REST APIs

Examples


16

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"

Problem: Phonebook App in Firebase


17

Open https://console.firebase.google.com/

Create a new project

Enable public
read / write
access

Solution: Setup a Firebase DB


18

Solution: Add Sample Data in Firebase


19

Solution: Test Your REST Service


20

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" />

<br>

<button id="btnCreate">Create</button>


21

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) { … }

});


22

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>"));

}


23

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


24

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('');

}


25

Solution: Phonebook in Firebase – JS Code

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

The correct contact key will come as parameter (due to binding)


Practice: jQuery AJAX

Live Exercises in Class (Lab)


27

AJAX sends asynchronous HTTP requests from JS

jQuery simplifies how developers use AJAX

Summary

$.ajax({ url, method: 'GET',

  success: displayRepos,

  error: displayError

});

function displayRepos(respos) { … }

function displayError(err) { … }

}


https://softuni.bg/courses/javascript-applications

AJAX and jQuery AJAX


License

This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license

29


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 @ YouTube

	youtube.com/SoftwareUniversity

	Software University Forums – forum.softuni.bg