Skip to content

Instantly share code, notes, and snippets.

@salami162
Last active December 15, 2015 22:19
Show Gist options
  • Save salami162/5332214 to your computer and use it in GitHub Desktop.
Save salami162/5332214 to your computer and use it in GitHub Desktop.
How to use $.ajax request. How to use $.Deferred()
/**
* submit function:
* - take userToken as a input parameter
* - request form schema with the userToken if it exists.
* - display form schema on the page.
*/
<div id="message"></div>
function submit (data) {
var request = $.ajax({
type: 'POST',
url: 'http://myserver.com/submit',
data: data
});
request.done(function (message) {
$('.message').html(message);
});
}
/**
* Add cross domain storage
*/
var Storage = function () {
this.domainUrl = 'http://thirdparty.com/storage';
};
// GET the data saved in the crossdomain storage.
Storage.prototype.get = function (key, fn) {
$.ajax({
type : 'GET',
url : this.domainUrl,
data : { key : key }
})
.done(function (data) {
fn(data);
})
.fail(function (error) {
fn({error : true});
});
}
// SAVE the data to the crossdomain storage.
Storage.prototype.set = function (key, value, fn) {
$.ajax({
type : 'POST',
url : this.domainUrl,
data : {
key : key,
data : value
}
})
.done(function (data) {
fn();
})
.fail(function (error) {
fn({error : true});
});
}
/**
* submit function.
* If no input data, use the crossdomain data
*/
function submit (data) {
if (!data) {
var storage = new Storage();
storage.get('data', function (data) {
submit(data || {});
});
}
else {
// AJAX request.
}
};
/**
* User $.Deferred()
*/
var Storage = function () {
this.domainUrl = 'http://thirdparty.com/storage';
};
// GET the data saved in the crossdomain storage.
Storage.prototype.get = function (key) {
return $.ajax({
type : 'GET',
url : this.domainUrl,
data : { key : key }
});
}
// SAVE the data to the crossdomain storage.
Storage.prototype.set = function (key, value) {
return $.ajax({
type : 'POST',
url : this.domainUrl,
data : {
key : key,
data : value
}
});
}
/**
* submit function.
* If no input data, use the crossdomain data
*/
function submit (data) {
if (data) {
var storage = new Storage();
var getDfd = storage.get('user');
getDfd.done(function (data) {
submit(data || {})
});
};
else {
// AJAX request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment