var root = '/Subscription';
var subscriptionsUploaded = 0;
//jQuery on document ready handler
$(function () {
//Show the busy indicator during ajax calls
$("#busy").hide();
$("#busy").ajaxStart(function () { $("#busy").show(); })
$("#busy").ajaxStop(function () { $("#busy").hide(); })
var x = $("#createSubscription");
//When the createSubscription button is clicked create a subscription
$("#create_subscription").click(createSubscriptionClick);
//When the sendData button is clicked retrieve the subscriptions stored in the local storage and send the data to the server
$("#send_data").click(sendDataClick);
//Define jQuery validation rules and execute the validation when the form is validated
$("#sub_form").validate({
rules: {
firstname: {
required: true,
minlength: 2
},
lastname: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
phone: {
required: true,
number: true,
minlength: 9,
maxlength: 9
}
},
messages: {
firstname: "",
lastname: "",
email: "",
phone: ""
}
});
});
function sendDataClick() {
//Iterate over the subscriptions stored in the local storage
for (var i = 0; i < window.localStorage.length; i++) {
//Retrieve the serialized subscription
var json = window.localStorage.getItem(window.localStorage.key(i));
try {
//Send the subscription to the server
sendData(
json,
//On success remove the subscription from the local storage
function (data) {
window.localStorage.removeItem(window.localStorage.key(data.Message));
subscriptionsUploaded++;
$("#resultmessage").html(subscriptionsUploaded + " subscriptions uploaded!");
},
//On error
function (xhr) {
alert(xhr.responseText);
});
}
catch (e) { alert(e); }
};
}
//Stores a subscription into the local storage
function createSubscriptionClick() {
//check the jQuery validation rules
if ($("#sub_form").valid()) {
var person = getSubscription();
//seialize the subscription
var jsData = JSON.stringify(person);
//store the subscription
window.localStorage.setItem($("#email").val(), jsData);
//update the resultMessage
$("#resultmessage").html($("#email").val() + " stored in local storage");
clearAll();
}
}
//Create a subscription object and bind to the input boxes values
function getSubscription() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var phone = $("#phone").val();
return { Firstname: firstname, Lastname: lastname, Email: email, Phone: phone };
}
//Clear the input boxes values
function clearAll() {
$("#firstname").attr("value", "");
$("#lastname").attr("value", "");
$("#email").attr("value", "");
$("#phone").attr("value", "");
}
//Ajax: post the json serilized subscriptions
function sendData(json, success, error) {
$.ajax({
url: root + '/save',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: success,
error: error
});
}