Working with data on the server

Today

JSON with servers

JSON is used for storing, sending and receiving data on servers.

If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server. In other words, you can save data by SENDing it to a server. (names, passwords, etc).

If you receive data in JSON format, you can convert it into a JavaScript object. In other words, you can GET data from a server.

JavaScript has the command JSON.parse() to turn JSON data into a Javascript object. By using this command, you can work with the data in your javascript code.

Example data from a server:

'{ "name":"Shane", "age":39, "city":"Los Angeles"}'

We use json.parse() to turn it into a Javascript object. The text must be written with proper JSON syntax or you will get an error.

var obj = JSON.parse( '{ "name":"Shane", "age":39, "city":"Los Angeles"}' );
<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>
var txt = '{"name":"Shane", "age":39, "city":"Los Angeles"}'
var obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

</body>
</html>

Sending data to a server

We previously covered parsing text into a JSON object to get data from a server (to display on a website for example).

To send data to a server, we need to convert the data into a string. We do this with JSON.stringify().

Example

var obj = { name: "Shane", age: 39, city: "Los Angeles" };

var myJSON = JSON.stringify(obj);

Loading JSON file with Jquery

Jquery gives us methods to make it easier to work with JSON.

A basic getJSON request is formatted as:

$.getJSON(url, data, success);

The url is local or remote. The data is optional, an object or strong sent to the server when requesting data, and success is an optional callback function to execute after the JSON request is successful.

example

function success(data) {
  // do something with data, which is an object
}

Finishing our Radio Project

For next week, finish your radio project solo or in a small group.

Requirements

The goal of this project is to complete the creation of your own custom web app for a radio station player. The application should be a unique and compellingly designed radio player that presents the user with a number of stations to select from. Selecting a station should cause the station to begin playing, and any previously selected station should stop. Beyond this, you may add any additional details and design elements you require.