jQuery AJAX request demo
by kazu69
HTML
<a href="#" id ="click">test</a>
<div id="output"> waiting for action </div>
CSS
a {
padding: 0.2em;
}
a:hover {
background-color: #02AAEE;
}
#output {
display: block;
margin-top: 8px;
padding: 1%;
border: 1px solid #666;
background-color: #efefef;
}
JavaScript
$(function() {
$('#click').on('click', function() {
var promise = getSuccessOutput();
promise.then(function(response) {
console.log(response)
$('#output').append('then: ' + response.greet);
})
})
});
function getSuccessOutput() {
return $.ajax({
url: '/echo/json/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {json: JSON.stringify({greet: 'Hello'})}
}).done(function(response) {
console.log(response);
$('#output').html('done: ' + response.greet + "\n")
}).fail(function(response) {
console.log(response);
});
}