Skip to content

Instantly share code, notes, and snippets.

@marijer
Last active December 28, 2015 13:29
Show Gist options
  • Save marijer/7508095 to your computer and use it in GitHub Desktop.
Save marijer/7508095 to your computer and use it in GitHub Desktop.
JQuery - AJAX - OOP & functiona, Utility and promises
/* Code school examples - return flight */
/* 1. AJAX calls - with all the different types */
$("#tour").on("click", "button", function() {
$.ajax('/photos.html', {
success: function(response) {
$('.photos').html(response).fadeIn();
},
error: function() {
$('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
},
timeout: 3000,
beforeSend: function () {
$('#tour').addClass('is-fetching');
},
complete: function () {
$('#tour').removeClass('is-fetching');
}
});
});
/* 2.1 JavaScript Objects - refactoring code */
// objects limits to one confirmation per page
var tour = {
init: function() {
$("#tour").on("click", "button", this.fetchPhotos);
},
fetchPhotos: function () {
$.ajax('/photos.html', {
data: {location: $("#tour").data('location')},
success: function(response) {
$('.photos').html(response).fadeIn();
},
error: function() {
$('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
},
timeout: 3000,
beforeSend: function() {
$('#tour').addClass('is-fetching');
},
complete: function() {
$('#tour').removeClass('is-fetching');
}
});
}
}
$(document).ready(function() {
tour.init();
});
/* 2.2 Javascript functions - refactoring code */
// Good to know: cannot access locally scoped variables >> makes it private
// JQuery can change the this value, in AJAX callbacks, this is set to AJAX settings
function Tour(el) {
var tour = this;
this.el = el;
this.fetchPhotos = function() {
$.ajax('/photos.html', {
data: {location: tour.el.data('location')},
context: tour,
success: function(response) {
this.el.find('.photos').html(response).fadeIn();
},
error: function() {
this.el.find('.photos').html('<li>There was a problem fetching the latest photos. Please try again.</li>');
},
timeout: 3000,
beforeSend: function() {
this.el.addClass('is-fetching');
},
complete: function() {
this.el.removeClass('is-fetching');
}
});
}
this.el.on('click', 'button', this.fetchPhotos);
}
$(document).ready(function() {
var paris = new Tour($('#paris'));
var london = new Tour($('#london'));
});
/* 3.1 AJAX with forms */
// want to send data over
$(document).ready(function() {
$('form').on('submit', function(event) {
event.preventDefault();
$.ajax('/book', {
type: 'POST', // set type as post
data: $('form').serialize(),
success: function(result) {
$('.tour').html (result);
}
});
});
});
/* 3.2 - AJAX with JSON */
// JSON - Javascript Object Notation - standard way to format data
$('form').on('submit', function(event) {
event.preventDefault();
$.ajax($('form').attr('action'), {
type: $('form').attr('method'),
data: $('form').serialize(),
dataType: 'json',
success: function(response) {
$('.tour').html('<p></p>')
.find('p')
.append('Trip to ' + response.description)
.append(' at $' + response.price)
.append(' for ' + response.nights + ' nights')
.append('. Confirmation: ' + response.confirmation);
}
});
});
/* 4. JQUERY UTILITIES */
// $.each(collection, function(<index>, <object>) {} )
$('button').on('click', function() {
$.getJSON('/cities/deals', function(result) {
$.each(result, function(index, dealItem) {
var dealElement = $('.deal-' + index);
dealElement.find('.name').html(dealItem.name);
dealElement.find('.price').html(dealItem.price);
});
});
});
// $.map( collection, function (<item>, <index>){ });
// Map returns an array modified by what is returned in the function passed as an argument
$('.update-available-flights').on('click', function() {
$.getJSON('/flights/late', function(result) {
var flightElements = $.map(result, function(flightItem, index){
var listItem = ('<li></li>');
return $('<li>'+flightItem.flightNumber+'-'+flightItem.time+'</li>');
});
$('.flight-times').html(flightElements);
});
});
// $.detach
// removes element from the DOM, while preserving all data and events
$('.update-available-flights').on('click', function() {
$.getJSON('/flights/late', function(result) {
var flightElements = $.map(result, function(flightItem, index){
var flightEl = $('<li>'+flightItem.flightNumber+'-'+flightItem.time+'</li>');
return flightEl;
});
$('.flight-times').detach() // gives the DOM a break but remembers data and events
.html(flightElements)
.appendTo('.flights');
});
});
/* 5.1 Advanced Events */
// Namespacing Events
$('button').on('click.weather', function() {
var results = $(this).closest('li').find('.results');
results.append('<p>Weather: 74&deg;</p>');
$(this).off('click.weather');
});
// Triggering Event (simulation)
$('button').trigger('click');
// Set Custom Event
$('button').on('show.weather', function() {
// do stuff
$(this).off('show.weather');
});
// Show Photos
$('button').on('click.photos', function() {
// do stuff
$(this).off('click.photos');
$(this).trigger('show.weather');
});
/* 5.2 JQuery plugins */
// create a plugin
$.fn.photofy = function() {
console.log (this);
};
$(document).ready(function() {
$('.tour').photofy();
});
// use extend to combine objects
$.fn.photofy = function(options) {
this.each(function() {
var show = function(e) {
e.preventDefault();
settings.tour
.addClass('is-showing-photofy')
.find('.photos')
.find('li:gt('+(settings.count-1)+')')
.hide();
}
var remove = function(e) {
e.preventDefault();
settings.tour.fadeOut().off('.photofy');
};
var settings = $.extend({
count: 3,
tour: $(this)
}, options);
settings.tour.on('click.photofy', '.see-photos', show);
settings.tour.on('show.photofy', show);
settings.tour.on('click.photofy', '.hide-tour', remove);
});
}
$(document).ready(function() {
$('.tour').photofy({ count: 1});
$('.show-photos').on('click', function(e) {
e.preventDefault();
$('.tour').trigger('show.photofy');
});
});
/* 6 Promises */
//$.Deferred sets promise
var promise = $.Deferred();
// done succesfully
promise.resolve(value);
//calls this function
promise.done(function(value){});
// when things are failing
promise.reject(value);
// calls this function
promise.fail(function (value){})
// object with promise
var Vacation = {
getPrice: function(location){
var promise = $.Deferred();
$.ajax({
url: '/vacation/prices',
data: {q: location},
success: function(result){
promise.resolve(result.price);
},
error: function () {
var error= "invalid error thingie";
promise.reject(error);
}
});
return promise;
}
}
// event that calls object
$(document).ready(function() {
$('button').on('click', function(){
var location = $('.location').text();
Vacation.getPrice(location)
.done(function(result){
$('.price').text(result); })
.fail(function(error){
console.log (error); });
});
});
// use $.when and $.then to set the order strictly, otherwise multiple things can load
// randomly
$(document).ready(function() {
$('button').on('click', function(){
var tour = $(this).parent();
var location = tour.data('location');
var resultDiv = tour.find('.results').empty();
$.when(
Vacation.getPrice(location),
Photo.getPhoto(location)
).then (function (priceResult, photoResult) {
$('<p>$'+priceResult+'</p>').appendTo(resultDiv);
$('<img />').attr('src', photoResult).appendTo(resultDiv);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment