AJAX Snippets
<script type='text/javascript'>
$(document).ready(function() {
$(function() {
var href;
var title;
$('body').on('click','a.ajax-link',function(e) { // nav link clicked
// get link href
href = $(this).attr("href");
// get input name
title = $(this).attr("name");
// load content via AJAX
loadContent(href);
// prevent click and reload
e.preventDefault();
$(".spinner").removeClass('uk-hidden');
});
function loadContent(url){ // Load content
// variable for page data
$pageData = '';
// send Ajax request
$.ajax({
type: "POST",
url: url,
data: { ajax: true },
success: function(data,status){
$pageData = data;
}
}).done(function(){ // when finished and successful
// remove old content
$('.ajax-current-content').remove();
// construct new content
$pageData = '<div class="ajax-current-content">' + $pageData + '</div>';
// add content to page
$('#ajax-container').append($pageData);
$(".spinner").addClass('uk-hidden');
}); // end of ajax().done()
} // end of loadContent()
});
});
</script>
<!-- links to call ajax content -->
<a class="ajax-link" href="<?=$pages->get('/search/')->url?>">Load Seach</a>
<a class="ajax-link" href="<?=$pages->get('/')->url?>">Load Home</a>
<!-- uikit spinner icons -->
<div class="spinner uk-hidden" uk-spinner></div>
<!-- replace ajax-current-content with new -->
<div id="ajax-container">
<div class="ajax-current-content">
<h3>This content will be replacer</h3>
</div>
</div>
$.ajax({
url: 'http://maps.googleapis.com/maps/api/geocode/json?address='+ location +'&sensor=false',
success: function(data) {
console.log(data);
}
});
/**
* Getting Data with Fetch
*/
fetch('https://api.github.com/users/lokomotivan/repos')
.then(response => response.json()) // (XML -> response.text() | image -> response.blob)
.then(data => {
// Here's a list of repos!
console.log(data)
});
/**
* Sending data with Fetch
*/
let content = {some: 'content'};
// The actual fetch request
fetch('some-url', {
method: 'post', // can be: post, put, del
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(content)
})
// .then()...
/**
* Fetch Error Handling
*/
fetch('https://api.github.com/users/chrissycoyier/repos')
.then(response => {
if (response.ok) {
return response.json()
} else {
return Promise.reject('something went wrong!')
}
})
.then(data => console.log('data is', data))
.catch(error => console.log('error is', error));
/**
* Fetch Error Handling FULL
*/
fetch('https://api.github.com/users/chrissycoyier/repos')
.then(response => {
if (response.ok) {
return response.json()
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText
})
}
})
.catch(error => {
if (error.status === 404) {
// do something about 404
}
})