I don't expect you to ever write this code, but here's the code that allows your browser to make a request to a server for data without reloading the page:
// Create a new request
var xhr = new XMLHttpRequest();
// Tell request that whenever readyState changes, call event handler
xhr.addEventListener("readystatechange", stateChanged);
function stateChanged(event) {
// If successfully returned back, then...
if (xhr.readyState == 4 && xhr.status == 200) {
// Success! Call the callback function!
// But first, parse the response as JSON
var results = JSON.parse(xhr.response);
var movies = results["Search"];
for (var i = 0; i < movies.length; i++) {
alert(movies[i]["Title"]);
}
}
});
// Open the connection and send it on its merry way
xhr.open("GET", url);
xhr.send();
What is it? Firebase makes a number of products for software developers building mobile or web applications. They take care of hosting the database and the back-end code, so you can just connect your front-end code and have persistent data -- aka data on your web page doesn't reset every time you refresh the page!
Get started with Firebase
How to add a new item to the Firebase database:
var firebase = new Firebase("https://blinding-inferno-7422.firebaseio.com");
// Sample data object, any key-value pairs will work
var mustang = {
make: "ford",
color: "red"
}
// Push new object to our database
firebase.push(mustang);
// Create an event listener for the 'child_added' event
// This is a method Firebase gives us access to
// It listens for anything new getting added to our database
firebase.on("child_added", function (snapshot) {
// A "snapshot" is a special Firebase concept. Just know that calling val()
// will give you back the data stored in the database.
var data = snapshot.val();
console.log(data);
})
Some useful Local Storage commands:
// To clear local storage (remove all entries)
localStorage.clear();
// To save something to local storage - similar to what firebase.push did above
localStorage.setItem("username", "avandamiri12345");
// Get or read something from Local Storage
localStorage.getItem("username");
In your application, you might use this to remember a user's username, even after a page refresh
// On page load, check Local Storage to see if there's already a username
var username = localStorage.getItem("username");
// If there is no username, ask the user and set value in local storage
if (username == null) {
username = prompt("What is your username?");
localStorage.setItem("username", username);
}