1 Web App Development 2 3 JavaScript: JSON JSON: J ava S cript O - - PowerPoint PPT Presentation

1
SMART_READER_LITE
LIVE PREVIEW

1 Web App Development 2 3 JavaScript: JSON JSON: J ava S cript O - - PowerPoint PPT Presentation

1 Web App Development 2 3 JavaScript: JSON JSON: J ava S cript O bject N otation. JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation. 4 Exchanging Data When exchanging data between a


slide-1
SLIDE 1

Web App Development

1

slide-2
SLIDE 2

2

slide-3
SLIDE 3

JavaScript: JSON

3

slide-4
SLIDE 4

4

JSON: JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.

slide-5
SLIDE 5

When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server. We can also convert any JSON received from the server into JavaScript objects. This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

Exchanging Data

5

slide-6
SLIDE 6

If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server: var myObj = {name: "John", age: 31, city: "New York"}; var myJSON = JSON.stringify(myObj); window.location = "demo_json.php?x=" + myJSON; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_send You will learn more about the JSON.stringify() function later in this tutorial.

Sending Data

6

slide-7
SLIDE 7

If you receive data in JSON format, you can convert it into a JavaScript object: var myJSON = '{"name":"John", "age":31, "city":"New York"}'; var myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_receive You will learn more about the JSON.parse() function later in this tutorial.

Receiving Data

7

slide-8
SLIDE 8

When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats. JSON makes it possible to store JavaScript objects as text. //Storing data: myObj = {name: "John", age: 31, city: "New York"}; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON); //Retrieving data: text = localStorage.getItem("testJSON");

  • bj = JSON.parse(text);

document.getElementById("demo").innerHTML = obj.name; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_store

Storing Data

8

slide-9
SLIDE 9

9

slide-10
SLIDE 10

▪ JSON stands for JavaScript Object Notation ▪ JSON is a lightweight data-interchange format ▪ JSON is "self-describing" and easy to understand ▪ JSON is language independent *

The JSON format was originally specified by Douglas Crockford.

What is JSON?

10

* JSON uses JavaScript syntax, but the JSON format is text only. Text can be read and used as a data format by any programming language.

slide-11
SLIDE 11

Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any programming language. JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects: JSON.parse() So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

Why use JSON?

11

slide-12
SLIDE 12

12

https://api.svsu.edu/courses?courseNumber=255

slide-13
SLIDE 13

JavaScript: JSON

13

slide-14
SLIDE 14

The JSON syntax is a subset of the JavaScript syntax.

14

slide-15
SLIDE 15

JSON syntax is derived from JavaScript object notation syntax:

▪ Data is in name/value pairs ▪ Data is separated by commas ▪ Curly braces hold objects ▪ Square brackets hold arrays

JSON Syntax Rules

15

slide-16
SLIDE 16

JSON data is written as name/value pairs. A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: "name":"John"

JSON Data - A Name and a Value

16

JSON names require double quotes. JavaScript names don't.

slide-17
SLIDE 17

The JSON format is almost identical to JavaScript objects. In JSON, keys must be strings, written with double quotes: { "name":"John" } In JavaScript, keys can be strings, numbers, or identifier names: { name:"John" }

JSON - Evaluates to JavaScript Objects

17

slide-18
SLIDE 18

In JSON, values must be one of the following data types:

▪ a string ▪ a number ▪ an object (JSON object) ▪ an array ▪ a boolean ▪ Null

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:

▪ a function ▪ a date ▪ undefined

JSON Values

18

slide-19
SLIDE 19

In JSON, string values must be written with double quotes: { "name":"John" } In JavaScript, you can write string values with double or single quotes: { name:'John' }

JSON Values Continued

19

slide-20
SLIDE 20

Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript. With JavaScript you can create an object and assign data to it, like this: var person = { name: "John", age: 31, city: "New York" }; You can access a JavaScript object like this: // returns John person.name; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_access

JSON Uses JavaScript Syntax

20

slide-21
SLIDE 21

It can also be accessed like this: // returns John person["name"]; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_access2 Data can be modified like this: person.name = "Gilbert"; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_modify_object

JSON Uses JavaScript Syntax Continued

21

slide-22
SLIDE 22

It can also be modified like this: person["name"] = "Gilbert"; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_modify_object2 You will learn how to convert JavaScript objects into JSON later in this tutorial.

JSON Uses JavaScript Syntax Continued

22

slide-23
SLIDE 23

The same way JavaScript objects can be used as JSON, JavaScript arrays can also be used as JSON. You will learn more about arrays as JSON later in this tutorial.

JavaScript Arrays as JSON

23

slide-24
SLIDE 24

▪ The file type for JSON files is ".json" ▪ The MIME type for JSON text is "application/json"

JSON Files

24

slide-25
SLIDE 25

JavaScript: JSON

25

slide-26
SLIDE 26

Both JSON and XML can be used to receive data from a web server.

26

slide-27
SLIDE 27

The following JSON and XML examples both define an employees object, with an array of 3 employees: JSON Example {"employees":[ { "firstName":"John", "lastName":"Doe" }, { "firstName":"Anna", "lastName":"Smith" }, { "firstName":"Peter", "lastName":"Jones" } ]} XML Example <employees> <employee> <firstName>John</firstName> <lastName>Doe</lastName> </employee> <employee> <firstName>Anna</firstName> <lastName>Smith</lastName> </employee> <employee> <firstName>Peter</firstName> <lastName>Jones</lastName> </employee> </employees>

JSON vs XML

27

slide-28
SLIDE 28

▪ JSON doesn't use end tag ▪ JSON is shorter ▪ JSON is quicker to read and write ▪ JSON can use arrays

The biggest difference is: XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

JSON is Unlike XML Because

28

slide-29
SLIDE 29

For AJAX applications, JSON is faster and easier than XML: Using XML

▪ Fetch an XML document ▪ Use the XML DOM to loop through the document ▪ Extract values and store in variables

Using JSON

▪ Fetch a JSON string ▪ JSON.Parse the JSON string

Why JSON is Better Than XML

29

XML is much more difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object.

slide-30
SLIDE 30

JavaScript: JSON

30

slide-31
SLIDE 31

In JSON, values must be one of the following data types:

▪ a string ▪ a number ▪ an object (JSON object) ▪ an array ▪ a boolean ▪ null

JSON values cannot be one of the following data types:

▪ a function ▪ a date ▪ undefined

Valid Data Types

31

slide-32
SLIDE 32

Strings in JSON must be written in double quotes. { "name":"John" }

JSON Strings

32

slide-33
SLIDE 33

Numbers in JSON must be an integer or a floating point. { "age":30 }

JSON Numbers

33

slide-34
SLIDE 34

Values in JSON can be objects. { "employee":{ "name":"John", "age":30, "city":"New York" } }

JSON Objects

34

Objects as values in JSON must follow the same rules as JSON objects.

slide-35
SLIDE 35

Values in JSON can be arrays. { "employees":[ "John", "Anna", "Peter" ] }

JSON Arrays

35

slide-36
SLIDE 36

Values in JSON can be true/false. { "sale":true }

JSON Booleans

36

slide-37
SLIDE 37

Values in JSON can be null. { "middlename":null }

JSON null

37

slide-38
SLIDE 38

JavaScript: JSON

38

slide-39
SLIDE 39

A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object.

39

slide-40
SLIDE 40

Imagine we received this text from a web server: '{ "name":"John", "age":30, "city":"New York"}’ Use the JavaScript function JSON.parse() to convert text into a JavaScript object: var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Example - Parsing JSON

40

Make sure the text is written in JSON format, or else you will get a syntax error.

slide-41
SLIDE 41

Use the JavaScript object in your page: <p id="demo"></p> <script> document.getElementById("demo").innerHTML = obj.name + ", " +

  • bj.age;

</script> Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_parse

Example - Parsing JSON Continued

41

slide-42
SLIDE 42

You can request JSON from the server by using an AJAX request As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object. Use the XMLHttpRequest to get data from the server: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "json_demo.txt", true); xmlhttp.send(); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax Take a look at json_demo.txt

JSON From the Server

42

slide-43
SLIDE 43

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object. The JSON returned from the server is an array: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr[0]; } }; xmlhttp.open("GET", "json_demo_array.txt", true); xmlhttp.send(); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax_array Take a look at json_demo_array.txt

Array as JSON

43

slide-44
SLIDE 44

Date objects are not allowed in JSON. If you need to include a date, write it as a string. You can convert it back into a date object later: var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}'; var obj = JSON.parse(text);

  • bj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " +

  • bj.birth;

Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_parse_date

Exceptions – Parsing Dates

44

slide-45
SLIDE 45

Or, you can use the second parameter, of the JSON.parse() function, called reviver. The reviver parameter is a function that checks each property, before returning the value. Convert a string into a date, using the reviver function: var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}'; var obj = JSON.parse(text, function (key, value) { if (key == "birth") { return new Date(value); } else { return value; }}); document.getElementById("demo").innerHTML = obj.name + ", " +

  • bj.birth;

Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_parse_reviver

Exceptions – Parsing Dates Continued

45

slide-46
SLIDE 46

Functions are not allowed in JSON. If you need to include a function, write it as a string. You can convert it back into a function later: var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}'; var obj = JSON.parse(text);

  • bj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age(); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_parse_function You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.

Exceptions – Parsing Functions

46

slide-47
SLIDE 47

The JSON.parse() function is included in all major browsers and in the latest ECMAScript (JavaScript) standard: For older browsers, a JavaScript library is available at https://github.com/douglascrockford/JSON-js.

Browser Support

47

Web Browsers Support

  • Firefox 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
slide-48
SLIDE 48

JavaScript: JSON

48

slide-49
SLIDE 49

A common use of JSON is to exchange data to/from a web server. When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify().

49

slide-50
SLIDE 50

Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify() to convert it into a string. var myJSON = JSON.stringify(obj);

Stringify a JavaScript Object

50

The result will be a string following the JSON notation.

slide-51
SLIDE 51

myJSON is now a string, and ready to be sent to a server: var obj = { name: "John", age: 30, city: "New York" }; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_stringify You will learn how to send JSON to the server in the next chapter.

Stringify a JavaScript Object Continued

51

slide-52
SLIDE 52

It is also possible to stringify JavaScript arrays: Imagine we have this array in JavaScript: var arr = [ "John", "Peter", "Sally", "Jane" ]; Use the JavaScript function JSON.stringify() to convert it into a string. var myJSON = JSON.stringify(arr);

Stringify a JavaScript Array

52

The result will be a string following the JSON notation.

slide-53
SLIDE 53

myJSON is now a string, and ready to be sent to a server: var arr = [ "John", "Peter", "Sally", "Jane" ]; var myJSON = JSON.stringify(arr); document.getElementById("demo").innerHTML = myJSON; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_stringify_array You will learn how to send JSON to the server in the next chapter.

Stringify a JavaScript Array Continued

53

slide-54
SLIDE 54

In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings. var obj = { name: "John", today: new Date(), city : "New York" }; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_stringify_date You can convert the string back into a date object at the receiver.

Exceptions – Stringify Dates

54

slide-55
SLIDE 55

In JSON, functions are not allowed as object values. The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value: var obj = { name: "John", age: function () {return 30;}, city: "New York"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_stringify_function

Exceptions – Stringify Functions

55

slide-56
SLIDE 56

This can be omitted if you convert your functions into strings before running the JSON.stringify() function. var obj = { name: "John", age: function () {return 30;}, city: "New York" };

  • bj.age = obj.age.toString();

var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_stringify_function_tostring You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.

Exceptions – Stringify Functions Continued

56

slide-57
SLIDE 57

The JSON.stringify() function is included in all major browsers and in the latest ECMAScript (JavaScript) standard:

Browser Support

57

Web Browsers Support

  • Firefox 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
slide-58
SLIDE 58

JavaScript: JSON

58

slide-59
SLIDE 59

{ "name":"John", "age":30, "car":null } JSON objects are surrounded by curly braces {}. JSON objects are written in key/value pairs. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon. Each key/value pair is separated by a comma.

Object Syntax

59

slide-60
SLIDE 60

You can access the object values by using dot (.) notation: myObj = { "name":"John", "age":30, "car":null }; x = myObj.name; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_dot You can also access the object values by using bracket ([]) notation: myObj = { "name":"John", "age":30, "car":null }; x = myObj["name"]; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_bracket

Accessing Object Values

60

slide-61
SLIDE 61

You can loop through object properties by using the for-in loop: myObj = { "name":"John", "age":30, "car":null }; for (x in myObj) { document.getElementById("demo").innerHTML += x; } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_loop In a for-in loop, use the bracket notation to access the property values: myObj = { "name":"John", "age":30, "car":null }; for (x in myObj) { document.getElementById("demo").innerHTML += myObj[x]; } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_loop_bracket

Looping an Object

61

slide-62
SLIDE 62

Values in a JSON object can be another JSON object. myObj = { "name":"John", "age":30, "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" } } You can access nested JSON objects by using the dot notation or bracket notation: x = myObj.cars.car2; //or: x = myObj.cars["car2"]; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_nested

Nested JSON Objects

62

slide-63
SLIDE 63

You can use the dot notation to modify any value in a JSON object: myObj.cars.car2 = "Mercedes"; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_modify You can also use the bracket notation to modify a value in a JSON object: myObj.cars["car2"] = "Mercedes"; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_modify_bracket

Modify Values

63

slide-64
SLIDE 64

Use the delete keyword to delete properties from a JSON object: delete myObj.cars.car2; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_delete

Delete Object Properties

64

slide-65
SLIDE 65

JavaScript: JSON

65

slide-66
SLIDE 66

[ "Ford", "BMW", "Fiat" ] Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

Arrays as JSON Objects

66

slide-67
SLIDE 67

Arrays can be values of an object property: { "name":"John", "age":30, "cars":[ "Ford", "BMW", "Fiat" ] }

Arrays in JSON Objects

67

slide-68
SLIDE 68

You access the array values by using the index number: x = myObj.cars[0]; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_array_access

Accessing Array Values

68

slide-69
SLIDE 69

You can access array values by using a for-in loop: for (i in myObj.cars) { x += myObj.cars[i]; } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_array_loop_in Or you can use a for loop: for (i = 0; i < myObj.cars.length; i++) { x += myObj.cars[i]; } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_array_loop

Looping Through an Array

69

slide-70
SLIDE 70

Values in an array can also be another array, or even another JSON object: myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ] }

Nested Arrays in JSON Objects

70

slide-71
SLIDE 71

To access arrays inside arrays, use a for-in loop for each array: for (i in myObj.cars) { x += "<h1>" + myObj.cars[i].name + "</h1>"; for (j in myObj.cars[i].models) { x += myObj.cars[i].models[j]; } } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_array_nested

Nested Arrays in JSON Objects Continued

71

slide-72
SLIDE 72

Use the index number to modify an array: myObj.cars[1] = "Mercedes"; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_array_modify

Modify Array Values

72

slide-73
SLIDE 73

Use the delete keyword to delete items from an array: delete myObj.cars[1]; Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_array_delete

Delete Array Items

73

slide-74
SLIDE 74

JavaScript: JSON

74

slide-75
SLIDE 75

A common use of JSON is to read data from a web server, and display the data in a web page. This chapter will teach you how to exchange JSON data between the client and a PHP server.

75

slide-76
SLIDE 76

PHP has some built-in functions to handle JSON. Objects in PHP can be converted into JSON by using the PHP function json_encode(): <?php $myObj->name = "John"; $myObj->age = 30; $myObj->city = "New York"; $myJSON = json_encode($myObj); echo $myJSON; ?> Show PHP file: https://www.w3schools.com/js/showphp.asp?filename=demo_file

The PHP File

76

slide-77
SLIDE 77

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above: Use JSON.parse() to convert the result into a JavaScript object: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "demo_file.php", true); xmlhttp.send(); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_simple

The Client JavaScript

77

slide-78
SLIDE 78

Arrays in PHP will also be converted into JSON when using the PHP function json_encode(): <?php $myArr = array("John", "Mary", "Peter", "Sally"); $myJSON = json_encode($myArr); echo $myJSON; ?> Show PHP file: https://www.w3schools.com/js/showphp.asp?filename=demo_file_array

PHP Array

78

slide-79
SLIDE 79

Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above: Use JSON.parse() to convert the result into a JavaScript array: var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; } }; xmlhttp.open("GET", "demo_file_array.php", true); xmlhttp.send(); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_array

The Client JavaScript

79

slide-80
SLIDE 80

PHP is a server side programming language, and should be used for operations that can only be performed by a server, like accessing a database. Imagine you have a database on the server, containing customers, products, and suppliers. You want to make a request to the server where you ask for the first 10 records in the "customers" table: Use JSON.stringify() to convert the JavaScript object into JSON:

  • bj = { "table":"customers", "limit":10 };

dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true); xmlhttp.send(); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db

PHP Database

80

slide-81
SLIDE 81

Example explained:

▪ Define an object containing a table property and a limit property. ▪ Convert the object into a JSON string. ▪ Send a request to the PHP file, with the JSON string as a parameter. ▪ Wait until the request returns with the result (as JSON) ▪ Display the result received from the PHP file.

PHP Database Continued

81

slide-82
SLIDE 82

Take a look at the PHP file: <?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $stmt = $conn->prepare("SELECT name FROM ? LIMIT ?"); $stmt->bind_param("ss", $obj->table, $obj->limit); $stmt->execute(); $result = $stmt->get_result(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?> PHP File explained:

▪ Convert the request into an object, using the PHP function json_decode(). ▪ Access the database, and fill an array with the requested data. ▪ Add the array to an object, and return the object as JSON using the json_encode() function.

PHP Database Continued

82

slide-83
SLIDE 83

Convert the result received from the PHP file into a JavaScript object, or in this case, a JavaScript array: Use JSON.parse() to convert the JSON into a JavaScript object: ... xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } }; ... Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_loop

Loop Through the Result

83

slide-84
SLIDE 84

When sending data to the server, it is often best to use the HTTP POST method. To send AJAX requests using the POST method, specify the method, and the correct header. The data sent to the server must now be an argument to the .send() method:

  • bj = { "table":"customers", "limit":10 };

dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } }; xmlhttp.open("POST", "json_demo_db_post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post

PHP Method = POST

84

slide-85
SLIDE 85

The only difference in the PHP file is the method for getting the transferred data. Use $_POST instead of $_GET: <?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_POST["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $stmt = $conn->prepare("SELECT name FROM ? LIMIT ?"); $stmt->bind_param("ss", $obj->table, $obj->limit); $stmt->execute(); $result = $stmt->get_result(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>

PHP Method = POST Continued

85

slide-86
SLIDE 86

JavaScript: JSON

86

slide-87
SLIDE 87

JSON can very easily be translated into JavaScript. JavaScript can be used to make HTML in your web pages.

87

slide-88
SLIDE 88

Make an HTML table with data received as JSON:

  • bj = { table: "customers", limit: 20 };

dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); txt += "<table border='1'>" for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; } txt += "</table>" document.getElementById("demo").innerHTML = txt; } } xmlhttp.open("POST", "json_demo_db_post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_table

HTML Table

88

slide-89
SLIDE 89

Make the HTML table based on the value of a drop down menu: <select id="myselect" onchange="change_myselect(this.value)"> <option value="">Choose an option:</option> <option value="customers">Customers</option> <option value="products">Products</option> <option value="suppliers">Suppliers</option> </select> <script> function change_myselect(sel) { var obj, dbParam, xmlhttp, myObj, x, txt = "";

  • bj = { table: sel, limit: 20 };

dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); txt += "<table border='1'>" for (x in myObj) { txt += "<tr><td>" + myObj[x].name + "</td></tr>"; } txt += "</table>" document.getElementById("demo").innerHTML = txt; } }; xmlhttp.open("POST", "json_demo_db_post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); } </script> Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_table_dynamic

Dynamic HTML Table

89

slide-90
SLIDE 90

Make an HTML drop down list with data received as JSON:

  • bj = { table: "customers", limit: 20 };

dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); txt += "<select>" for (x in myObj) { txt += "<option>" + myObj[x].name; } txt += "</select>" document.getElementById("demo").innerHTML = txt; } } xmlhttp.open("POST", "json_demo_db_post.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam); Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_html_select

HTML Drop Down List

90

slide-91
SLIDE 91

JavaScript: JSON

91

slide-92
SLIDE 92

JSONP is a method for sending JSON data without worrying about cross-domain issues. JSONP does not use the XMLHttpRequest object. JSONP uses the <script> tag instead.

92

slide-93
SLIDE 93

Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object. <script src="demo_jsonp.php">

JSONP Intro

93

JSONP stands for JSON with Padding.

slide-94
SLIDE 94

The file on the server wraps the result inside a function call: <?php $myJSON = '{ "name":"John", "age":30, "city":"New York" }'; echo "myFunc(".$myJSON.");"; ?> Show PHP file: https://www.w3schools.com/js/showphp.asp?filename=demo_jsonp The result returns a call to a function named "myFunc" with the JSON data as a parameter. Make sure that the function exists on the client.

The Server File

94

slide-95
SLIDE 95

The function named "myFunc" is located on the client, and ready to handle JSON data: function myFunc(myObj) { document.getElementById("demo").innerHTML = myObj.name; } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_jsonp

The JavaScript function

95

slide-96
SLIDE 96

The example above will execute the "myFunc" function when the page is loading, based

  • n where you put the script tag, which is not very satisfying.

The script tag should only be created when needed: Create and insert the <script> tag when a button is clicked: function clickButton() { var s = document.createElement("script"); s.src = "demo_jsonp.php"; document.body.appendChild(s); } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_jsonp_create

Creating a Dynamic Script Tag

96

slide-97
SLIDE 97

The examples above are still very static. Make the example dynamic by sending JSON to the php file, and let the php file return a JSON object based on the information it gets. <?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj- >$limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo "myFunc(".json_encode($outp).")"; ?>

Dynamic JSONP Result

97

slide-98
SLIDE 98

PHP File explained:

▪ Convert the request into an object, using the PHP function json_decode(). ▪ Access the database, and fill an array with the requested data. ▪ Add the array to an object. ▪ Convert the array into JSON using the json_encode() function. ▪ Wrap "myFunc()" around the return object.

Dynamic JSONP Result Continued

98

slide-99
SLIDE 99

JavaScript Example The "myFunc" function will be called from the php file: function clickButton() { var obj, s

  • bj = { table: "products", limit: 10 };

s = document.createElement("script"); s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj); document.body.appendChild(s); } function myFunc(myObj) { var x, txt = ""; for (x in myObj) { txt += myObj[x].name + "<br>"; } document.getElementById("demo").innerHTML = txt; } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_jsonp_php

Dynamic JSONP Result Continued

99

slide-100
SLIDE 100

When you have no control over the server file, how do you get the server file to call the correct function? Sometimes the server file offers a callback function as a parameter: The php file will call the function you pass as a callback parameter: function clickButton() { var s = document.createElement("script"); s.src = "jsonp_demo_db.php?callback=myDisplayFunction"; document.body.appendChild(s); } Try it Yourself: https://www.w3schools.com/js/tryit.asp?filename=tryjson_jsonp_callback

Callback Function

100

slide-101
SLIDE 101

JavaScript: JSON

101