Skip to content

Instantly share code, notes, and snippets.

@jrobber
Created October 23, 2015 17:30
Show Gist options
  • Save jrobber/3cbd1a6443a3b1963b75 to your computer and use it in GitHub Desktop.
Save jrobber/3cbd1a6443a3b1963b75 to your computer and use it in GitHub Desktop.
Basic Ajax example
$(document).ready(function(){
//var = selector getting the app
var app = $('#ajax-app');
//var = template that is a header that says 'jquery Ajax!
var header = $('<h1>jQuery Ajax!</h1>');
//var = template that is a button that says get Data
var getButton = $('<button>Get Data</button>');
//var = template that is a button that says clear
var clearButton = $('<button>Clear Data</button>');
//var = template for a list (ul)
var list = $('<ul></ul>');
//Append each of those to the DOM
app.append(header);
app.append(getButton);
app.append(clearButton);
app.append(list);
//listen for the get data button click and fire an ajax call to
getButton.on('click', function(){
getData();
})
function getData(){
$.ajax({
method: 'GET',
url: 'https://gist.githubusercontent.com/coolaj86/e67b9131d58e22b8b585/raw/photos.json'
}).then(function(data){
setTimeout(function(){
var dataObj = JSON.parse(data);
showData(dataObj);
}, 2000);
});
list.append($('<li>Getting Data</li>'));
}
function showData(data){
list.children().remove();
for(var i = 0; i < data.length; i++){
var item = data[i];
var listItem = $('<li></li>');
var image = $('<img src="' + item.url + '"></img>')
listItem.text(item.name);
listItem.append(image);
list.append(listItem);
}
}
//https://gist.githubusercontent.com/coolaj86/e67b9131d58e22b8b585/raw/photos.json
//in the callback console log the data
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Empty Night</title>
</head>
<body>
<div id="ajax-app"></div>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="code.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment