Problem in adding data through admin.firestore() - javascript

My current firestore rules in my project:
service cloud.firestore {
match /databases/{database}/documents {
match /auth_url/{auth_doc} {
allow read, write: if request.auth.uid != null;
}
match /nonauth_url/{nonauth_doc}{
allow read, write: if false ;
}
}
}
auth_url collection is for authorized users and running perfectly (addition, creation, deletion etc of documents) and nonauth_url collection is for non authenticated users, by jquery post request through client.js I'm adding data by using admin.firestore() in my server (index.js) but in my cloud firestore section there is no data present there. Are my firestore rules wrong somewhere ?
client.js
function renderList(user){
let db = firebase.firestore() ;
stopListner = db.collection('auth_url').doc(user.email).onSnapshot( (doc) => {
var objOfObj = doc.data() ;
let newarrOfObjects = [] ;
for( key in objOfObj){
newarrOfObjects.push(Object.assign(objOfObj[key], {name: key})) ;
}
$('.container.urlsList').html('') ;
newarrOfObjects.forEach( (obj, pos) => {
if( obj.code != ''){
$('.container.urlsList').append(`
<div id="accordion${pos+1}" class="myUrlSlot">
<div class="card">
<div class="card-header d-flex flex-row align-items-center p-2">
<button class="btn btn-outline-dark rounded-circle" data-toggle="collapse" data-target="#${pos+1}"><i class="fa fa-plus"></i></button>
<div class="w-100 code font-weight-bold">
${obj.code}
</div>
<button data-edit-id="${pos+1}"class="btn btn-outline-primary edit rounded-circle"><i class="fa fa-pencil"></i></button>
<button data-del-id="${pos+1}" class="btn btn-outline-danger del rounded-circle"><i class="fa fa-trash"></i></button>
</div>
<div id="${pos+1}" class="collapse info">
<dl class='m-3'>
<dt>Shortened URL</dt>
<dd>${window.location.origin+ '/' + obj.code}</dd>
<dt>Redirection URL</dt>
<dd class="redirectUrl">${obj.redirectUrl}</dd>
</dl>
</div>
</div>
</div>
`) ;
}
}) ;
if( $('div.urlsList').children().length == 0){
$('#emptyMsg').show() ;
}
else{
$('#emptyMsg').hide() ;
}
// changing plus to minus vice-versa
$('.collapse').on('show.bs.collapse', function(){
$(this).parent().find('.fa-plus').removeClass('fa-plus').addClass('fa-minus') ;
}).on('hidden.bs.collapse', function(){
$(this).parent().find('.fa-minus').removeClass('fa-minus').addClass('fa-plus') ;
}) ;
// edit icon
$('.edit').click(function(){
let target_id = $(this).data('edit-id') ;
bootbox.dialog({
title: 'Change Redirection URL',
centerVertical: true,
closeButton: false,
message: `
<form id="changeUrlForm">
<label for="inputUrl">Enter the New Url</label>
<input type="url" class="form-control text-center" id="inputUrl" name="iurl" placeholder="Enter URL Here">
</form>
`,
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-danger'
},
ok: {
label: 'Ok',
className: 'btn-primary',
callback: function(){
$('#changeUrlForm').validate({
rules: {
iurl: {
required: true,
url: true
}
},
messages: {
iurl: {
url: 'Please enter a valid url with "http://" or "https://" first !!'
}
}
}) ;
if( $('#changeUrlForm').valid()){
let newurl = $('#inputUrl').val() ;
var objToBeUpdated = `url${target_id}` ;
var updateObj = {} ;
updateObj[`${objToBeUpdated}.redirectUrl`] = newurl ;
db.collection('auth_url').doc(user.email).update(updateObj).then( () => {
successAlert(`URL${target_id}'s redirection url updated successfully !!`) ;
}).catch( err => {
errorAlert(err.code, err.message) ;
}) ;
}
else{
$('label.error').addClass('text-danger');
return false ;
}
}
}
}
}) ;
}) ;
// del icon
$('.del').click(function(){
let target_id = $(this).data('del-id') ;
bootbox.confirm({
message: 'Are you sure you want to delete this saved URL ?',
centerVertical: true,
closeButton: false,
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function(result){
if(result){
var updateObj = {
[`url${target_id}`]: {
code: '',
redirectUrl: ''
}
} ;
db.collection('auth_url').doc(user.email).update(updateObj).then(() => {
successAlert(`URL${target_id} deleted successfully !!`) ;
}).catch( err => {
errorAlert(err.code, err.message) ;
});
}
}
}) ;
}) ;
}, (err) => {
errorAlert(err.code, err.message) ;
}) ;
}
$(function(){
// on authorization endering is working perfectly fine
firebase.auth().onAuthStateChanged( user => {
if( user ){
if( firebase.auth().currentUser.emailVerified == false ){
bootbox.dialog(verifyDialogSettings);
}
if( firebase.auth().currentUser.providerData[0].providerId === 'google.com'){
$('.changePass, .beforechangePass').hide() ;
}
refreshMainPage( user ) ;
// refreshUrls(user.email) ;
console.log('signed in state') ;
$('.login, #newurl, .mainTopic, .middle').hide() ;
$('.signOutButton, .settings, .welcomemsg, .image, .description, .urlsList').show() ;
// refresh the list
renderList(user) ;
}
else{
console.log('signed out state') ;
$('.signOutButton, .settings, .welcomemsg, .image, .description, .urlsList, #emptyMsg').hide() ;
$('.login, #newurl, .mainTopic, .middle').show() ;
}
});
$('.sendUrl').on('click', function(e){
e.preventDefault() ;
$('#nonauthForm').validate({
rules: {
url_nauth: {
required: true,
url: true
}
}
}) ;
if( $('#nonauthForm').valid()){
$.post('/nonauth_url',{
URL: $('#url').val()
},function(code, status){
if(status === 'success'){
$('#newurl').html(`
${window.location.origin+ '/'+ code}
`)
}
}) ;
}
else{
$('label.error').addClass('text-danger d-block mt-2');
}
}) ;
}) ;
index.js (server)
const functions = require('firebase-functions');
const admin = require('firebase-admin') ;
const express = require('express') ;
const urlId = require('shortid') ;
const sp = require('synchronized-promise') ;
const string = require('randomstring') ;
const serviceAccount = require('./url-shortner-xxxx.json') ;
const app = express() ;
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let db = admin.firestore() ;
let Data = db.collection('nonauth_url') ;
app.post('/nonauth_url', (req, res) => {
let codeGenerated = 'n' + urlId.generate() ; // n for non-authenticated users
let docname = 'doc-' + string.generate(4) ;
let schema = {
code: codeGenerated,
url: req.body.URL,
expiredAt: Date.now()+600000 // in milisceonds for 10min
}
let docRef = Data.doc(docname).set(schema) ;
res.send(schema.code) ;
}) ;
exports.routeFunc = functions.https.onRequest(app) ;
res.send(schema.code) is sending back the code but not creating any docs under nonauth_url collection

Sending an HTTP response indicates the end of execution for a running function. You need to wait for the set() to complete before responding:
let docRef = Data.doc(docname).set(schema).then(() => {
res.send(schema.code);
});

Related

How to get methods inside vue, the methods is googlemap api?

I have some google maps api that i've already craeted in javascript, but, for some time my collagues decided to use vue framework on the apps.
I tried to put my initMap of my googlemaps javascript inside vue methods and trye to call it on windows.initmap outside vue app, but it doesn't work,
here are my javascript code bellow
let base_url = '{{ envx('APP_BASE_URL') }}';
let cdn = '{{ envx('CDN_ENDPOINT') }}';
let endpoint = '{{ envx('API_ENDPOINT') }}';
addEventListener('load', () => {
const {
createApp
} = Vue;
const initialState = () => {
return {
containerClass: 'container-grid',
loading: false,
properties: <?= json_encode($list_properti) ?>,
filter: {
page: 1,
limit: 12,
keyword: '',
harga: '',
status_unit: '',
jenis: '',
id_propinsi: '',
}
}
}
const app = createApp({
data() {
return initialState()
},
methods: {
checkData() {
console.log(this.properties.DATA);
},
getPropertiImage(imageUrl) {
const urlOnly = `{{ file_exists('${imageUrl}') }}`
if (urlOnly) return base_url + 'assets/img/no-data.png'
if (imageUrl === null) return base_url + 'assets/img/no-data.png'
const checkImage = imageUrl.split("")
const getFlag = [checkImage[0], checkImage[1]].join("")
if (getFlag !== '1|') return base_url + 'assets/img/no-data.png'
return imageUrl.replace('1|', cdn + '?key=')
},
setToBillions(item) {
let price = item;
let idrPrices = `{{ rupiah((float) '${price}') }}`;
let prices = idrPrices.split('.');
if (prices.length > 3) {
return [prices[0], prices[1]].join('.') + " Juta";
}
return idrPrices;
},
cicilan(val) {
let cicilan = (val / 1000000).toFixed(1);
if (cicilan < 1) {
return 'Rp.' + (cicilan * 1000).toLocaleString('id-ID') + 'rb/bln';
}
return 'Rp.' + cicilan.toLocaleString('id-ID') + 'jt/bln';
},
getAvatar(url) {
if (url) {
let explodeAva = url.split('|member');
if (explodeAva.length == 2) {
return cdn + '?key=member' + explodeAva[1];
}
return url;
}
return base_url + 'assets/img/avatar/1552FBA78C75D6FBA33F.png';
},
changePage(id) {
if (this.loading) {
return false;
}
document.getElementById('container-loading').scrollIntoView({
behavior: 'auto',
block: 'start',
inline: 'nearest'
});
this.filter.page = id;
this.updateContent()
this.initMap()
},
async initMap() {
const centerPosition = {
lat: -1.6160679698214473,
lng: 117.38277669882174
}
let map = new google.maps.Map(document.getElementById("container-map"), {
center: centerPosition,
zoom: 5,
});
const areaProperties = []
for (const properti of this.properties.DATA) {
const exampleUrl = `{{ envx('CDN_ENDPOINT') }}?key=`;
let imageUrl = properti.GBR1;
imageUrl = imageUrl.replace('1|', exampleUrl);
const urlAvatar = ``
let imageMember = properti.AVATAR_MEMBER;
const imageAvatar = imageMember.replace('1|', imageMember);
const propertiAreas = {
position: new google.maps.LatLng(properti.LATITUDE, properti.LONGITUDE),
content: ` <template v-if="!loading" v-for="(properti, index) in properties.DATA">
<div class="card card-container card-shadow card--radius mb-2">
<div class="img-container">
<div class="img-top">
<div class="badge-report bg-colors-blue" v-html="properti.JENIS_PROPERTI"></div>
</div>
<img class="card-img-top img-card" v-bind:src="'' + getPropertiImage(properti.GBR1)"
alt="''+ properti.NAMA">
</div>
<div class="card--body m-4">
<small class="d-flex gap-2 align-items-center text-dim">
<img src="assets/img/shape/location.png" class="icon-location" height="12">
<div style="width: 100%; text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap; "
v-html="properti.ALAMAT"></div>
</small>
<h4 v-html="properti.NAMA"></h4>
<small class="text-dim">Mulai dari</small>
<h3 v-html="'Rp. '+ setToBillions(properti.HARGA)"></h3>
<small class="text-dim d-block">Cicilan dari <b class="text-black"
style="font-family: 'Futura'" v-html="cicilan(properti.CICILAN)"></b></small>
<small class="text-dim d-block">Suku Bunga <b class="text-black"
style="font-family: 'Futura'" v-html="'Dari '+ properti.BUNGA + '%'"></b></small>
<small class="d-flex gap-2 align-items-center mt-2"
style="font-size: 12px; color: var(--c-blue); font-family: 'FuturaMD';">
<img src="'' + getAvatar(properti.AVATAR_MEMBER)" height="25" class="rounded-circle">
<div v-html="properti.NAMA_AGEN"></div>
</small>
</div>
<div class="card-label--foot bandingkan-button" role="button" #onclick="handleCompare()">
Bandingkan
</div>
</div>
</template>
`
}
areaProperties.push(propertiAreas)
}
var infowindow = new google.maps.InfoWindow();
const icon = {
url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Pro 6.2.1 by #fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M36.8 192H603.2c20.3 0 36.8-16.5 36.8-36.8c0-7.3-2.2-14.4-6.2-20.4L558.2 21.4C549.3 8 534.4 0 518.3 0H121.7c-16 0-31 8-39.9 21.4L6.2 134.7c-4 6.1-6.2 13.2-6.2 20.4C0 175.5 16.5 192 36.8 192zM64 224V384v80c0 26.5 21.5 48 48 48H336c26.5 0 48-21.5 48-48V384 224H320V384H128V224H64zm448 0V480c0 17.7 14.3 32 32 32s32-14.3 32-32V224H512z"/></svg>'
),
scaledSize: new google.maps.Size(20, 20)
}
let marker, i;
for (i = 0; i < areaProperties.length; i++) {
marker = new google.maps.Marker({
position: areaProperties[i].position,
icon: icon,
map: map,
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(areaProperties[i].content);
infowindow.open(map, marker);
}
})(marker, i));
}
},
// async updateContent() {
async updateContent() {
this.loading = true;
this.containerClass = 'w-full'
const filterData = this.filter;
const filterStrings = []
const lastKey = Object.keys(filterData).pop();
for (const key in filterData) {
if (filterData[key] !== "" || filterData[key] !== null) {
filterStrings.push(key)
filterStrings.push('=')
filterStrings.push(filterData[key])
if (key !== lastKey) {
filterStrings.push('&')
}
}
}
//FIXME string zero values
const params = filterStrings.join('')
await $.ajax({
type: 'get',
dataType: 'json',
url: base_url + 'api/properti/list-properti?' + params,
success: res => {
this.properties = res;
}
})
this.loading = false;
this.containerClass = 'container-grid'
}
}
}).mount('#app')
window.initMap = app.initMap();
})
And here is the error that i got
How could i solve this?
You shouldn't call window.initMap = app.initMap(); after creating the Vue instance but rather in the mounted lifecycle hook:
mounted() {
window.initMap = app.initMap();
}

2 Dropzone on the same page

Currently I have a form with dropzone.js and it works correctly, but the form must be 2 times on the same page, only the styles change when I insert the second form only the first one remains working
I don't know what changes I should make
Currently I have a form with dropzone.js and it works correctly, but the form must be 2 times on the same page, only the styles change when I insert the second form only the first one remains working
I don't know what changes I should make
script
<code>
var Onyx = {
defaults: {
debug: true
},
/**
* Function to print results in the console if the above debug is true
**/
log: function() {
if (Onyx.defaults.debug === true) {
var argsArray = [],
printOut = "console.log(args)";
for ( var i = 0; i < arguments.length; i++ ) {
argsArray.push("args[" + i + "]");
}
printOut = new Function( "args", printOut.replace( /args/, argsArray.join(",") ) );
printOut(arguments);
}
},
/**
* Firing functions and bindings and other important stuff
**/
init: function(e) {
if ( $("#the-planner-form").length ) {
Onyx.projectPlanner();
if ( $("body").data("form-completed") == "yes" ) {
setTimeout(function() {
Onyx.plannerShowSuccess(true)
}, 800)
}
}
},
/**
* Project planner
**/
projectPlanner: function() {
Onyx.initDropzone();
var checkedValues = [];
// Add default checked service
$('input[name="planner_project_type_checkbox"]:checked').each(function() {
$(this).val();
checkedValues.push($(this).val())
});
$('input[name="planner_project_type"]').val(checkedValues.join(", "));
$('div.type-selection').each(function() {
$(this).on("click", function(e) {
e.preventDefault();
if ( $(this).find('input[checked]').length ) {
checkedValues.splice( $.inArray($(this).find('input[checked]').val(), checkedValues), 1 );
$(this).find('input[checked]').removeAttr('checked');
$('input[name="planner_project_type"]').val(checkedValues);
Onyx.log($.inArray($(this).find('input[name="planner_project_type_checkbox"]').val(), checkedValues));
Onyx.log(checkedValues);
} else {
$(this).find('input[name="planner_project_type_checkbox"]').attr('checked', true);
checkedValues.push($(this).find('input[name="planner_project_type_checkbox"]').val());
$('input[name="planner_project_type"]').val(checkedValues.join(", "));
Onyx.log(checkedValues);
Onyx.log($.inArray($(this).find('input[name="planner_project_type_checkbox"]').val(), checkedValues));
}
});
});
var sendingForm = false;
$("form#the-planner-form").bind("submit", function(e) {
e.preventDefault();
// Check every thing is valid
$('form#the-planner-form').find(".validate").each(function() {
sendingForm = 0 != Onyx.plannerValidate($(this));
});
if (sendingForm) {
$(".error-msg").stop().animate({
opacity: 0
}, 300, function () { $(this).hide() });
if ( matchMedia("only screen and (max-height: 1023px)").matches || matchMedia("only screen and (max-width: 600px)").matches ) {
$("html,body").stop().animate({
scrollTop: 0
}, 500);
}
Onyx.plannerShowSpinner();
$.ajax({
type: "POST",
url: window.location + "/send_form.php",
data: $("#the-planner-form").serialize()
}).done(function (status, textStatus, jqXHR) {
Onyx.log("Planner form status: " + status);
Onyx.log("Planner form textStatus: " + textStatus);
Onyx.log(jqXHR);
if ( jqXHR.status == 200 && textStatus == 'success' ) {
Onyx.plannerShowSuccess();
} else {
Onyx.plannerShowSpinner(false);
alert("Something went wrong");
}
});
} else {
$(".error-msg").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300), false
}
});
},
plannerShowSpinner: function(showSpinner) {
if ("undefined" == typeof showSpinner) var showSpinner = true;
if ( showSpinner ) {
$(".form-controls, .fields-group").stop().animate({
opacity: 0
}, 400, function() {
$(this).hide();
$(".form-spinner").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300)
});
} else {
$(".form-spinner").stop().animate({
opacity: 1
}, 300, function() {
$(this).hide();
$(".form-controls, .fields-group").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 400)
});
}
},
plannerShowSuccess: function(showSuccess) {
if ("undefined" == typeof showSuccess) var showSuccess = false;
var showThankyou = function() {
$(".form-spinner").stop().animate({
opacity: 0
}, 150, function() {
$(this).hide();
$(".form-thankyou-wrap").stop().css({
display: "block",
opacity: 0
}).animate({
opacity: 1
}, 300)
})
};
showSuccess ? $(".form-controls").stop().animate({
opacity: 0
}, 400, function() {
$(this).hide(), showThankyou()
}) : showThankyou()
},
/**
* Upload button
**/
dropzone_active: false,
updateDropzoneCount: function() {
var uploadedCount = $(".dz-preview.dz-success").length,
finalText = "";
if ( uploadedCount == 1 ) {
finalText = uploadedCount + " Archivo Subido.";
} else if ( uploadedCount == 0 ) {
finalText = "No subiste ningún archivo.";
} else {
finalText = uploadedCount + " Archivos Subidos.";
}
$(".total-uploaded").text(finalText)
},
initDropzone: function(e) {
Dropzone.autoDiscover = false;
Dropzone.options.plannerFilesDropzone = {
paramName: "form_file",
maxFilesize: 10,
maxFiles: 5,
acceptedFiles: "image/*,application/pdf,.doc,.docx,.xls,.xlsx,.csv,.tsv,.ppt,.pptx,.pages,.odt,.rtf",
url: window.location + "/file-upload.php",
addRemoveLinks: true,
forceFallback: false,
clickable: true,
/**
* The text used before any files are dropped.
*/
dictDefaultMessage: "Drop files here to upload.", // Default: Drop files here to upload
/**
* The text that replaces the default message text it the browser is not supported.
*/
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", // Default: Your browser does not support drag'n'drop file uploads.
/**
* If the filesize is too big.
* `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
*/
dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.", // Default: File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.
/**
* If the file doesn't match the file type.
*/
dictInvalidFileType: "You can't upload files of this type.", // Default: You can't upload files of this type.
/**
* If the server response was invalid.
* `{{statusCode}}` will be replaced with the servers status code.
*/
dictResponseError: "Server responded with {{statusCode}} code.", // Default: Server responded with {{statusCode}} code.
/**
* If `addRemoveLinks` is true, the text to be used for the cancel upload link.
*/
dictCancelUpload: "Cancel upload.", // Default: Cancel upload
/**
* The text that is displayed if an upload was manually canceled
*/
dictUploadCanceled: "Upload canceled.", // Default: Upload canceled.
/**
* If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
*/
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", // Default: Are you sure you want to cancel this upload?
/**
* If `addRemoveLinks` is true, the text to be used to remove a file.
*/
dictRemoveFile: "Remove file", // Default: Remove file
/**
* If this is not null, then the user will be prompted before removing a file.
*/
dictRemoveFileConfirmation: null, // Default: null
/**
* Displayed if `maxFiles` is st and exceeded.
* The string `{{maxFiles}}` will be replaced by the configuration value.
*/
dictMaxFilesExceeded: "You can not upload any more files.", // Default: You can not upload any more files.
/**
* Allows you to translate the different units. Starting with `tb` for terabytes and going down to
* `b` for bytes.
*/
dictFileSizeUnits: {tb: "TB", gb: "GB", mb: "MB", kb: "KB", b: "b"},
init: function() {
Onyx.dropzone_active = true;
$("input[name=form_file]").remove();
this.on("addedfile", function(file) {
$('button[type="submit"]').attr("disabled", "disabled");
Onyx.updateDropzoneCount();
});
this.on("removedfile", function(file) {
Onyx.log('Start removing file!');
$.ajax({
type: "POST",
url: window.location + "/file-upload.php",
data: {
target_file: file.upload_ticket,
delete_file: 1
},
sucess: function(jqXHR, textStatus){},
complete: function(jqXHR, textStatus){
var response = JSON.parse(jqXHR.responseText);
// Handle success
if (response.status === 'success') {
Onyx.log('Success: ' + response.info);
}
// Handle error
else {
Onyx.log('Error: ' + response.info);
}
}
});
var inputField = $("input[name=form_files_list]"),
filesArray = inputField.val().split(","),
fileIndex = $.inArray(file.upload_ticket, filesArray);
fileIndex !== -1 && filesArray.splice(fileIndex, 1);
inputField.val(filesArray.length > 0 ? filesArray.join(",") : "");
Onyx.updateDropzoneCount();
});
this.on("success", function(file, response) {
let parsedResponse = JSON.parse(response);
file.upload_ticket = parsedResponse.file_link;
var inputField = $("input[name=form_files_list]"),
filesArray = [];
Onyx.log(file.upload_ticket);
if ( "" != inputField.val() ) {
filesArray = inputField.val().split(",");
}
filesArray.push(file.upload_ticket);
inputField.val(filesArray.length > 0 ? filesArray.join(",") : "");
// Something to happen when file is uploaded
});
this.on("complete", function(file) {
if ( 0 === this.getUploadingFiles().length && 0 === this.getQueuedFiles().length ) {
$('button[type="submit"]').removeAttr("disabled");
}
Onyx.updateDropzoneCount()
});
this.on("error", function(file, t, a) {
this.removeFile(file);
});
}
};
$("#planner-files-dropzone").dropzone();
$("#planner-files-dropzone .instructions").click(function(e) {
var t = Dropzone.forElement("#planner-files-dropzone");
t.hiddenFileInput.click();
e.preventDefault()
})
},
plannerValidate: function(e) {
if ("" == e.val()) return e.addClass("error"), false;
if (!e.is('[type="email"]')) return e.removeClass("error"), true;
var t = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(e.val());
return t ? void 0 : (e.addClass("error"), false)
}
};
$(function() {
Onyx.init();
});
<?php
$delete_file = 0;
if(isset($_POST['delete_file'])){
$delete_file = $_POST['delete_file'];
}
$targetPath = dirname( __FILE__ ) . '/uploads/';
// Check if it's an upload or delete and if there is a file in the form
if ( !empty($_FILES) && $delete_file == 0 ) {
// Check if the upload folder is exists
if ( file_exists($targetPath) && is_dir($targetPath) ) {
// Check if we can write in the target directory
if ( is_writable($targetPath) ) {
/**
* Start dancing
*/
$tempFile = $_FILES['form_file']['tmp_name'];
$targetFile = $targetPath . $_FILES['form_file']['name'];
// Check if there is any file with the same name
if ( !file_exists($targetFile) ) {
// Upload the file
move_uploaded_file($tempFile, $targetFile);
// Be sure that the file has been uploaded
if ( file_exists($targetFile) ) {
$response = array (
'status' => 'success',
'file_link' => $targetFile
);
} else {
$response = array (
'status' => 'error',
'info' => 'Couldn\'t upload the requested file :(, a mysterious error happend.'
);
}
/*$response = array (
'status' => 'success',
'file_link' => 'Just a test, don\'t take it seriously.'
);*/
} else {
// A file with the same name is already here
$response = array (
'status' => 'error',
'info' => 'A file with the same name is exists.',
'file_link' => $targetFile
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'The specified folder for upload isn\'t writeable.'
);
}
} else {
$response = array (
'status' => 'error',
'info' => 'No folder to upload to :(, Please create one.'
);
}
// Return the response
echo json_encode($response);
exit;
}
// Remove file
if( $delete_file == 1 ){
$file_path = $_POST['target_file'];
// Check if file is exists
if ( file_exists($file_path) ) {
// Delete the file
unlink($file_path);
// Be sure we deleted the file
if ( !file_exists($file_path) ) {
$response = array (
'status' => 'success',
'info' => 'Successfully Deleted.'
);
} else {
// Check the directory's permissions
$response = array (
'status' => 'error',
'info' => 'We screwed up, the file can\'t be deleted.'
);
}
} else {
// Something weird happend and we lost the file
$response = array (
'status' => 'error',
'info' => 'Couldn\'t find the requested file :('
);
}
// Return the response
echo json_encode($response);
exit;
}
?>
<form action="#" method="post" id="the-planner-form" enctype="multipart/form-data">
<div class="text-cotizador">
<h1>COTIZADOR ONLINE</h1>
</div>
<div class="img-cotizador">
<img src="images/barrita-dorada.png" alt="ubicacion" width="35" height="5">
</div>
<div class="text-cotizador">
<p>Envíenos la foto de la joya a cotizar, y un tasador especializado<br>
la analizará y le brindará <b>el mejor precio del mercado.</b>
</p>
</div>
<div class="fields-group clearfix">
<div class="fields-group-controls1">
<div class="form-field half first">
<input type="text" name="planner_name" id="name" class="validate" placeholder="Nombre">
</div>
</div>
<div class="fields-group-controls2">
<div class="form-field half first">
<input type="email" name="planner_email" id="email" class="validate" placeholder="E-mail">
</div>
<div class="form-field half last">
<input type="tel" name="planner_phone" id="phone" class="validate" placeholder="Telefono">
</div>
</div>
<div class="fields-group-controls">
<div class="form-field">
<textarea name="planner_project_description" id="description" class="validate" placeholder="Comentarios"></textarea>
</div>
<div class="form-field">
<div id="files-wrap">
<div id="planner-files-dropzone">
<div class="dropzone-foo">
<div class="instructions is-desktop">ARRASTRA Y SUELTA AQUÍ LOS ARCHIVOS</br>o</div>
<div class="instructions is-touch">Subi los archivos</div>
</div>
<div class="total-uploaded">No se ha seleccionado ningún archivo</div>
</div>
<input type="hidden" value="" name="form_files_list" />
<input type="file" name="form_file" id="pp-file" />
</div>
<div class="text-formatos">
<p>Puede seleccionar hasta 5 imágenes | Tamaño máximo por imagen: 100 MB<br>Formatos admitidos: gif, png, jpg, jpeg
</p>
</div>
</div>
</div>
</div>
<div class="form-spinner-container">
<div class="form-spinner"></div>
</div>
<div class="form-thankyou-wrap">
<div class="form-thankyou-wrap-inner">
<div class="form-thankyou-content">
<h2><em>Gracias!</em> su mensaje ha sido enviado correctamente.</h2>
<p>Te contactaremos en poco tiempo..</p>
Go back to home page
</div>
</div>
</div><!-- .form-thankyou-wrap -->
<div class="form-controls">
<button aria-label="Send" type="submit">Enviar</button>
<div class="error-msg">Debe diligenciar toda la información. ↑</div>
</div>
</form>

How to upload in a particular folder of google drive?

I am having html form and gs.code as shown below. Its working perfect but files are uploaded in root folder of google drive. I want my files to upload in particular folder. Please help me.
Even i want to know how to use uploadView.setIncludeFolders(true) to show particular folder and subfolder for selection and upload.
var config = {
DEVELOPER_KEY: 'xxxx',
UPLOAD_FOLDER_ID: 'xxx',
ACCEPTED_FOLDER_ID: 'xxx',
TIME_ZONE: "GMT",
DATE_FORMAT: "MM/dd/yyyy HH:mm:ss",
ALLOWED_FILES: [
// MimeType.BMP,
// MimeType.GIF,
MimeType.pdf
// MimeType.PNG,
// MimeType.SVG,
// MimeType.PDF,
// MimeType.CSS,
// MimeType.CSV,
// MimeType.HTML,
// MimeType.JAVASCRIPT,
// MimeType.PLAIN_TEXT,
// MimeType.RTF,
// MimeType.OPENDOCUMENT_GRAPHICS,
// MimeType.OPENDOCUMENT_PRESENTATION,
// MimeType.OPENDOCUMENT_SPREADSHEET,
// MimeType.OPENDOCUMENT_TEXT,
// MimeType.MICROSOFT_EXCEL,
// MimeType.MICROSOFT_EXCEL_LEGACY,
// MimeType.MICROSOFT_POWERPOINT,
// MimeType.MICROSOFT_POWERPOINT_LEGACY,
// MimeType.MICROSOFT_WORD,
// MimeType.MICROSOFT_WORD_LEGACY,
// MimeType.ZIP
]
}
function doGet( e ){
return HtmlService.createHtmlOutputFromFile( "Form.html" ).setSandboxMode( HtmlService.SandboxMode.IFRAME )
}
function getConfig(){
DriveApp.getRootFolder();
return {
DEVELOPER_KEY: config.DEVELOPER_KEY,
TOKEN: ScriptApp.getOAuthToken(),
UPLOAD_FOLDER_ID: config.UPLOAD_FOLDER_ID
}
}
function verifyUpload( upload ){
var acceptedFolder = DriveApp.getFolderById( config.ACCEPTED_FOLDER_ID ),
uploadFolder = DriveApp.getFolderById( config.UPLOAD_FOLDER_ID ),
date = Utilities.formatDate( new Date(), config.TIME_ZONE, config.DATE_FORMAT ),
success = [],
fail = [],
doc,
file,
name
for( var i = 0; i < upload.docs.length; i++ ){
doc = upload.docs[ i ];
file = DriveApp.getFileById( doc.id );
name = file.getName();
if ( config.ALLOWED_FILES.indexOf( doc.mimeType ) >= 0 ){
success.push( name );
acceptedFolder.addFile( file );
uploadFolder.removeFile( file );
} else {
fail.push( name );
}
file.setName( upload.username + " - " + date + " - " + name);
}
return {
success: success,
fail: fail
}
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<style>
.app {
margin: 50px 0 0 30px;
}
.formholder {
background-color: #eee;
padding: 25px;
min-width: 400px;
max-width: 40%
}
input[type="text"] {
width: 300px;
}
</style>
</head>
<html>
<body>
<div class="app">
<div class="block formholder">
<div class="block form-group">
<label for="username">Name<span class="current">*</span>
</label>
<input type="text" id="username" class="width-100">
</div>
<div class="block">
<button class="blue" id="run-filepicker-interface">Choose File/s to Upload</button>
</div>
<div class="block">
</a>
</div>
</div>
<div class="block">
<div class="block" id="success-output"></div>
<div class="block error" id="error-output"></div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var fileUploadApp = {
config: {
DIALOG_DIMENSIONS: {
width: 600,
height: 425
}
},
init: function() {
google.script.run
.withSuccessHandler(fileUploadApp.setup)
.withFailureHandler(fileUploadApp.system.outputError)
.getConfig()
},
setup: function(config) {
$.extend(fileUploadApp.config, config)
gapi.load('picker', {
'callback': function() {
$('#run-filepicker-interface').click(fileUploadApp.runFilePickerInterface);
}
});
},
runFilePickerInterface: function(event) {
fileUploadApp.system.clearOutput()
var username = $("#username").val()
if (username) {
var config = fileUploadApp.config
$('#run-filepicker-interface').prop("disabled", false)
var uploadView = new google.picker.DocsUploadView()
uploadView.setIncludeFolders(false)
var picker = new google.picker.PickerBuilder()
.addView(uploadView)
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.hideTitleBar()
.setOAuthToken(config.TOKEN)
.setDeveloperKey(config.DEVELOPER_KEY)
.setCallback(fileUploadApp.pickerCallback)
.setSize(config.DIALOG_DIMENSIONS.width, config.DIALOG_DIMENSIONS.height)
.setOrigin(google.script.host.origin)
.setSelectableMimeTypes('application/vnd.google-apps.folder')
.build();
picker.setVisible(true);
} else {
fileUploadApp.system.outputError("Name is required.")
}
},
pickerCallback: function(data) {
switch (data.action) {
case google.picker.Action.PICKED:
var upload = {
username: $("#username").val(),
docs: []
}
$.each(data.docs, function(index, value) {
if (value.uploadState == "success")
upload.docs.push({
id: value.id,
mimeType: value.mimeType
})
})
google.script.run
.withSuccessHandler(fileUploadApp.verifyUploadSuccess)
.withFailureHandler(function(msg) {
$('#run-filepicker-interface').prop("disabled", false)
fileUploadApp.system.outputError(msg)
})
.verifyUpload(upload)
fileUploadApp.system.outputSuccess("Verifying uploaded files.")
break;
case google.picker.Action.CANCEL:
$('#run-filepicker-interface').prop("disabled", false)
break;
case google.picker.Action.LOADED:
// actions here
break;
}
},
verifyUploadSuccess: function(verifyResult) {
fileUploadApp.system.clearOutput()
if (verifyResult.success.length) {
fileUploadApp.system.outputSuccess(
"Fail:<br />" +
verifyResult.success.join("<br />")
)
}
if (verifyResult.fail.length) {
fileUploadApp.system.outputError(
"Success:<br />" +
verifyResult.fail.join("<br />")
)
}
$('#run-filepicker-interface').prop("disabled", false)
},
system: {
outputError: function(msg) {
$("#error-output").html(msg)
},
outputSuccess: function(msg) {
$("#success-output").html(msg)
},
clearOutput: function() {
$("#error-output, #success-output").html("")
}
}
}
function init() {
fileUploadApp.init()
}
</script>
<script src="https://apis.google.com/js/api.js?onload=init"></script>
</html>

How add WP comments via AJAX

I what create custom wordpress reply comment form and send data via ajax js , but when i send data to back are comments not show in admin panel. But status sending data is "OK" ( i cheked chrome console -> network ), how i can connect correctly front whith backend ? Whehere my mistake in this code ?
html
<div class="reply_comments respoond" style="display: none;">
<a class="cancel-comment-reply-link" style="display:none;">Cancel</a>
<form class="comment-form fcommentform">
<div class="comment-form-field-plus">
<label>Name:</label>
<input type="text" class="author" name="name">
<label>Email:</label>
<input type="text" class="email" name="email">
<textarea name="comment" class="comment" rows="5" cols="5" required></textarea>
</div>
<div class="form-footer">
<input class="like-post-button submit-comment-button rsubmit" type="button" value="<?php echo __('POST MY REVIEW', 'slotstory.com'); ?>" />
</div>
</form>
</div>
js
$('.rsubmit').on('click', function() {
$(this).closest('.fcommentform').submit();
});
$('.fcommentform').on('submit', function(e){
var errors = {
'name' : true,
'email' : true,
'comment' : true
};
e.preventDefault();
$(this).find('[name]').each(function( index ) {
var name = $( this ).attr('name');
var functionName = false;
switch(name){
case 'name':
functionName = _validateField;
break;
case 'email':
functionName = _validateEmail;
break;
case 'comment':
functionName = _validateComment;
break;
}
if (functionName) {
functionName.call(this);
$( this ).on('input', functionName.bind(this));
}
});
function _validateEmail(){
if(this != document) {
$element = $( this );
var reg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!reg.test($element.val())) {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
function _validateField(){
if(this != document) {
$element = $( this );
if ($element.val() == '') {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
function _validateComment(){
if(this != document) {
$element = $( this );
if ($element.val().length <= 10) {
$element.addClass('error');
errors[$element.attr('name')] = true;
} else {
delete errors[$element.attr('name')];
$element.removeClass('error');
}
}
}
if (Object.keys(errors).length == 0) {
console.log('success');
}
$.ajax({
type : 'POST',
url: ajaxactionurl,
data: $(this).serialize() + '&action=ajaxcomments',
error: function (request, status, error) {
if( status == 500 ){
alert( 'Error while adding comment' );
} else if( status == 'timeout' ){
alert('Error: Server doesn\'t respond.');
} else {
var wpErrorHtml = request.responseText.split("<p>"),
wpErrorStr = wpErrorHtml[1].split("</p>");
alert( wpErrorStr[0] );
}
},
});
return false;
});
php
add_action( 'wp_ajax_ajaxcomments', 'custom_submit_ajax_comment' );
add_action( 'wp_ajax_nopriv_ajaxcomments', 'custom_submit_ajax_comment' );
function custom_submit_ajax_comment() {
global $wpdb;
$comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
if ( is_wp_error( $comment ) ) {
$error_data = intval( $comment->get_error_data() );
if ( ! empty( $error_data ) ) {
wp_die( '<p>' . $comment->get_error_message() . '</p>', __( 'Comment Submission Failure' ), array( 'response' => $error_data, 'back_link' => true ) );
} else {
wp_die( 'Unknown error' );
}
}
$comment_data = array(
'comment_post_ID' => $comment_post_ID,
'comment_content' => $comment,
'comment_parent' => $comment_parent,
'comment_date' => $time,
'comment_approved' => 0,
'user_id' => $current_user->ID,
);
exit();
}
The status is 200 ok because you don't send anything in the php.
I suggest checking the body of the response, not just the status code.
Start debugging there. Good luck.

How dynamically enable data- tag using JS, Telerik and Kendo UI?

I am using App Builder from Telerik with Kendo UI trying to build a SPA application. I am very new to using Telerik and Kendo UI, please forgive the code.
There are two things I am trying to accomplish.
Enable swipe to open and hide the login head image until the user is logged in.
When a user is logged out return to the login screen and disable swipe to open and hide the login header image.
I have tried adding: data-swipe-to-open="false" in the layout, using the .hide on the header in the layout. When I use data-swipe-to-open="false" the #appDrawer does not open (which is what I want) but I cannot set the data-swipe-to-open = true. I cannot find any documentation from Telerik.
Any and all feedback is appreciated.
Login screen as of now
Swipe on login
HTML
<!--Login View-->
<div id="tabstrip-login"
data-role="view"
data-title="Login"
data-model="app.loginService.viewModel"
data-before-show="app.loginService.beforeShow"
data-after-show="app.loginService.afterShow">
<div style="background-image:url(/xxxx.png); background-position:top; background-repeat:no-repeat; background-size:contain; background-color:white;">
<div style="min-width:325px; min-height:144px;"></div>
</div>
<div data-bind="visible: isLoggedIn">
<div data-bind="visible : isExpired">
Expired Card info
</div>
<div id="dvCardInfoContainer" class="panel panel-default " style="background-color:white;" data-bind="invisible : isExpired">
<div class="panel panel-body" style="background-image:url(img/xyx.png); background-size:cover; background-position:center; background-color:white; ">
<div style="display:flex; flex-flow: row nowrap; align-content:center; justify-content:center; align-items:center;">
<div class="dvVerticalTextContainerLeftSide"><div id="memberStatusTop" data-bind="text :memberStatus" class="dvVerticalTextLeftSide capText bold"></div></div>
<div class="dvCenterVerticalContainer">
<ul>
<li data-bind="text :attCompanyName"></li>
<li data-bind="text :attAircraftTypes"></li>
<li data-bind="text :attAircraftRegNum"></li>
<li class="bold" data-bind="text :attExpirationDate"></li>
<li data-bind="text :calcDateTillExp"></li>
</ul>
</div>
<div class="dvVerticalContainerRightSide"><div class="dvVerticalTextRightSide capText bold" data-bind="text :memberStatus" id="memberStatusBottom"></div></div>
</div>
<div id="goodStanding" class="text-center capText bold"> TEXT </div>
</div>
</div>
</div>
<form data-bind="events: { keyup: checkEnter }">
<ul data-role="listview" data-style="inset" data-bind="invisible: isLoggedIn">
<li>
<label>
<div>Username</div>
<input type="text" data-bind="value: username" />
</label>
</li>
<li>
<label>
<div>Password</div>
<input type="password" data-bind="value: password" />
</label>
</li>
</ul>
<input id="login" type="submit" data-role="button" data-bind="click: onLogin, invisible: isLoggedIn" value="Login" class="login-button" />
</form>
</div>
Layout
<div data-role="layout" data-id="tabstrip-layout">
<header id="hdr" data-role="header">
<div data-role="navbar" >
<span data-role="view-title"></span>
<a data-role="button" href="#appDrawer" data-rel="drawer" data-align="left" data-icon="details"></a>
</div>
</header>
<!-- application views will be rendered here -->
</div>
<div id="appDrawer" data-role="drawer" data-title="Navigation">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
</div>
</header>
<ul id="navigation-container" data-role="listview">
<li>Membership Card</li>
<li>Card Info</li>
<li><a onclick="app.clearLocalStorage();">Log Out</a> </li>
</ul>
</div>
app.js
(function (global) {
var app = global.app = global.app || {};
app.clearLocalStorage = function () {
localStorage.clear();
app.loginService.viewModel.set("isLoggedIn", false);
}
app.makeUrlAbsolute = function (url) {
var anchorEl = document.createElement("a");
anchorEl.href = url;
return anchorEl.href;
};
document.addEventListener("deviceready", function () {
navigator.splashscreen.hide();
app.changeSkin = function (e) {
var mobileSkin = "";
if (e.sender.element.text() === "Flat") {
e.sender.element.text("Native");
mobileSkin = "flat";
} else {
e.sender.element.text("Flat");
mobileSkin = "";
}
app.application.skin(mobileSkin);
};
var element = document.getElementById('appDrawer');
if (typeof (element) != 'undefined' && element !== null) {
if (window.navigator.msPointerEnabled) {
$('#navigation-container').on('MSPointerDown', 'a', function (event) {
app.keepActiveState($(this));
});
} else {
$('#navigation-container').on('touchstart', 'a', function (event) {
app.keepActiveState($(this));
});
}
}
app.application = new kendo.mobile.Application(document.body, { layout: "tabstrip-layout", skin: 'nova'});
//$("#hdr").hide();
// app.loginService.viewModel.set("isLoggedIn", true);
}, false);
app.removeActiveStatus = function _removeActiveState(item) {
var currentItem = item;
$('#navigation-container li a.active').removeClass('active');
currentItem.addClass('notActive');
}
app.keepActiveState = function _keepActiveState(item) {
var currentItem = item;
$('#navigation-container li a.active').removeClass('active');
currentItem.addClass('active');
};
app.isOnline = function () {
if (!navigator || !navigator.connection) {
return true;
} else {
return navigator.connection.type !== 'none';
}
};
})(window);
Login.js
function loadState() {
var cardData = localStorage.getItem("userAttributeList");
if (cardData) {
var obj = JSON.parse(localStorage.getItem("userAttributeList"));
var companyName = obj[0].attData;
var airCraftTypes = obj[23].attData;
var airCraftRegNum = obj[24].attData;
var memberType = obj[1].attData;
var x = obj[17].attData;//experation date
var daysTillExpire = app.loginService.viewModel.calcDate(x);
var expirationDate = app.loginService.viewModel.formatDate(x);
app.loginService.viewModel.set("attCompanyName", companyName);
app.loginService.viewModel.set("attAircraftTypes", airCraftTypes);
app.loginService.viewModel.set("attAircraftRegNum", airCraftRegNum);
app.loginService.viewModel.set("attExpirationDate", "Expires: " + expirationDate);
app.loginService.viewModel.set("calcDateTillExp", "Days to expiration: " + daysTillExpire);
var strMembershipDecision = "Paid Members";
if (strMembershipDecision == memberType) {
app.loginService.viewModel.set("memberStatus", "Prefered Member");
}
else { app.loginService.viewModel.set("memberStatus", "Trial Member"); }
if (daysTillExpire <= 0) {
app.loginService.viewModel.wipeout();
}
//app.loginService.viewModel.set("data-swipe-to-open", true);
$("#appDrawer").data("kendoMobileDrawer");
}
else { }
}
(function (global) {
var LoginViewModel,
app = global.app = global.app || {};
// default empty credentials
// configure the local-storage adapter
LoginViewModel = kendo.data.ObservableObject.extend({
userDataSoruce: null,
isLoggedIn: false,
isExpired: false,
showExpired: false,
username: "",
password: "",
authUrl: '',
userUrl: '',
groupUrl: '',
token: null,
groupId: "",
orgId: "",
userId: "",
cardData: null,
airCraftTypes: null,
expirationDate: null,
memberGroupStatus: null,
memberType: null,
airCraftRegNum: null,
companyName: null,
daysTillExpire: null,
onLogin: function () {
var that = this,
username = that.get("username").trim(),
password = that.get("password").trim();
if (username === "" || password === "") {
navigator.notification.alert("Both fields are required!",
function () { }, "Login failed", 'OK');
return;
}
this.getAuthToken();
},
onLogout: function () {
var that = this;
that.clearForm();
that.set("isLoggedIn", false);
},
clearForm: function () {
var that = this;
that.set("username", "");
that.set("password", "");
},
checkEnter: function (e) {
var that = this;
if (e.keyCode == 13) {
$(e.target).blur();
that.onLogin();
}
},
checkAuth: function (response) {
var that = this;
if (response) {
that.getCardInfo();
}
else { alert('Not success'); }
},
getAuthToken: function () {
var that = this, dataSource;
var response = false;
dataSource = new jQuery.ajax({
type: "POST",
url: that.authUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: 'apiKey=' + '&username=' + that.username + '&password=' + that.password,
username: that.username,
password: that.password,
success: function (data, status) {
that.token = data.token;
that.groupId = data.groupId;
that.orgId = data.orgId;
that.userId = data.userId;
response = true;
that.checkAuth(response);
localStorage.setItem("usertoken", data.token);
localStorage.setItem("username", that.username);
localStorage.setItem("password", that.password);
localStorage.setItem("groupId", data.groupId);
localStorage.setItem("orgId", data.orgId);
localStorage.setItem("userId", data.userId);
},
error: function (error) {
alert('Error in validing username and password.');
response = false;
that.checkAuth(response);
return false
}
});
},
getCardInfo: function () {
var that = this, datasoruce;
datasoruce = new jQuery.ajax({
type: "GET",
url: '' + that.userId + '/attribute',
contentType: "application/json",
dataType: "json",
headers: { 'Authorization': that.token },
success: function (data, status) {
localStorage.setItem("userAttributeList", JSON.stringify(data.attribute));
that.cardData = JSON.stringify(data.attribute);
that.loadData();
},
error: function (error) {
console.log(JSON.stringify(error));
}
})
},
loadData: function () {
var that = this;
var obj = JSON.parse(that.cardData);
that.companyName = obj[0].attData;
that.airCraftTypes = obj[23].attData;
that.airCraftRegNum = obj[24].attData;
var memberType = obj[1].attData;
var x = obj[17].attData;//experation date
that.daysTillExpire = this.calcDate(x);
that.expirationDate = this.formatDate(x);
that.set("attCompanyName", that.companyName);
that.set("attAircraftTypes", that.airCraftTypes);
that.set("attAircraftRegNum", that.airCraftRegNum);
that.set("attExpirationDate", "Expires: " + that.expirationDate);
that.set("calcDateTillExp", "Days to expiration: " + that.daysTillExpire);
that.set("isLoggedIn", true);
//checking for membership status
var strMembershipDecision = "Paid Members";
if (strMembershipDecision == memberType) {
that.set("memberStatus", "Prefered Member");
}
else { that.set("memberStatus", "Trial Member"); }
if (that.daysTillExpire <= 0) {
this.wipeout();
}
},
checkMembershipStatus: function (memberStatus, numDaysToExp) {
},
wipeout: function () {
var that = this;
that.set("isExpired", true);
that.set("showExpired", true);
},
formatDate: function (expirationDate) {
var date = new Date(); //date of experation
date.setYear(parseInt(expirationDate.substr(0, 4), 10));
date.setMonth(parseInt(expirationDate.substr(4, 2), 10) - 1);
date.setDate(parseInt(expirationDate.substr(6, 2), 10));
date.setHours(parseInt(expirationDate.substr(8, 2), 12)); // 201609290000
date.setMinutes(parseInt(expirationDate.substr(10, 2), 12));
return (date.toLocaleDateString());
},
calcDate: function (expirationDate) {
var date = new Date(); //date of experation
date.setYear(parseInt(expirationDate.substr(0, 4), 10));
date.setMonth(parseInt(expirationDate.substr(4, 2), 10) - 1);
date.setDate(parseInt(expirationDate.substr(6, 2), 10));
date.setHours(parseInt(expirationDate.substr(8, 2), 12)); // 201609290000
date.setMinutes(parseInt(expirationDate.substr(10, 2), 12));
var today = new Date(); //Setting todays date
today.setYear(today.getFullYear());
today.setMonth(today.getMonth());
today.setDate(today.getDate());
var millisecondsPerDay = (1000 * 60 * 60 * 24);
var millsBetween = (date.getTime() - today.getTime());
var numExpDays = Math.floor(millsBetween / millisecondsPerDay);
return (numExpDays);
}
});
app.loginService = {
viewModel: new LoginViewModel(),
afterShow: function () {
},
beforeShow: function () {
loadState();
},
//
// //loadState();
//var x = app.loginService.viewModel.get("companyName")
//alert(x);
// app.loginService.viewModel.isLoggedIn = true;
//logic to determine if user is logged in or not.
onShow: function () {
}
};
})(window);
I created a worked around using this
<a data-role="button" href="#appDrawer" data-rel="drawer" data-align="left" data-icon="details" data-bind="visible: isLoggedIn"></a>

Categories

Resources