NativeScript HTTP:getJSON doesn't work - telerik

I have used the original helloworld app and just change the model from HelloWorldModel to MainModel.
Then i required "http" but when i run the app and klik the button for "updateAction" it only writes to the console and sets the message.
The HTTP request doesn't do anything.
Code: (main-view-model.js)
var __extends = this.__extends || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
__.prototype = b.prototype;
d.prototype = new __();
};
var observable = require("data/observable");
var http = require("http");
var MainModel = (function(_super) {
__extends(MainModel, _super);
function MainModel() {
_super.call(this);
console.log("MainModel called");
this.set("message", "Last updated" + " 2015-07-22 00:00:00");
this.set("message2", "Last updated" + " 2015-07-22 00:00:00");
}
MainModel.prototype.updateAction = function() {
console.log("updateAction");
this.set("message2", "Last updated" + " 2015-07-22 01:00:00");
http.getJSON("https://httpbin.org/get").then(function(r) {
this.set("message", "Last updated \n" + r);
console.log("SUCCESS");
console.log(r);
}, function(e) {
// Argument (e) is Error!
console.log("FAIL");
console.log(e);
this.set("message", "Last updated \n" + e);
});
};
return MainModel;
})(observable.Observable);
exports.MainModel = MainModel;
exports.mainViewModel = new MainModel();
What am I doing wrong?
Note: I'm testing on iPhone 6 emulator

It seems that using getString works and gives the same response.
Still wierd the getJSON doesn't work.
A working example is:
http.getString("https://httpbin.org/get").then(function (r) {
console.log("SUCCESS");
console.log(r);
}, function (e) {
console.log("FAIL");
console.log(e);
});

Related

Service Worker "notificationclick" not firing

The notification is showing fine, but when I click on it, or any of the actions, nothing happens. I see no logging, no error messages, but the notification does close (although it closes even when I comment out the event.notification.close()).
I've tried using the Chrome debugger, and I can set a break point in the code that shows the notification, but all breakpoints within the notificationclick handler fail to pause execution.
I've spent days trying to get this to work and I'm at my wits' end.
const auth = firebase.auth();
const functions = firebase.functions();
const done = functions.httpsCallable("done");
const snooze = functions.httpsCallable("snooze");
self.addEventListener("notificationclick", event => {
console.log("notificationclick", event);
const uid = auth.currentUser.uid;
const { id, url } = event.notification.data;
event.notification.close();
event.waitUntil(() => {
switch (event.action) {
case "done":
console.log("Done");
return done({ uid, id });
case "snooze1":
console.log("Snooze 1 Hour");
return snooze({ uid, id, hours: 1 });
case "snooze24":
console.log("Snooze 1 Day");
return snooze({ uid, id, hours: 24 });
default:
console.log("Open App");
return clients
.matchAll({
includeUncontrolled: true,
type: "window"
})
.then(clientList => {
for (let i = 0; i < clientList.length; i++) {
let client = clientList[i];
if (url[0] === "#") {
if (client.url.endsWith(url) && "focus" in client) {
return client.focus();
}
} else {
if (
client.url.replace(/#.*$/, "") === url &&
"focus" in client
) {
return client.focus();
}
}
}
if (clients.openWindow) {
return clients.openWindow(location.origin + url);
}
});
}
});
});
firebase
.messaging()
.setBackgroundMessageHandler(({ data: { title, options } }) => {
options = JSON.parse(options);
options.actions = [
{ action: "done", title: "Done" },
{ action: "snooze1", title: "Snooze 1 Hour" },
{ action: "snooze24", title: "Snooze 1 Day" }
];
return self.registration.showNotification(title, options);
});
Hi Could you try below code and see if this is getting called-
self.addEventListener('notificationclick', function (event) {
event.notification.close();
var redirectUrl = null;
var tag = event.notification.tag;
if (event.action) {
redirectUrl = event.action
}
if (redirectUrl) {
event.waitUntil(async function () {
var allClients = await clients.matchAll({
includeUncontrolled: !0
});
var chatClient;
for (const client of allClients) {
if (redirectUrl != '/' && client.url.indexOf(redirectUrl) >= 0) {
client.focus();
chatClient = client;
break
}
}
if (chatClient == null || chatClient == 'undefined') {
chatClient = clients.openWindow(redirectUrl);
return chatClient
}
}().then(result => {
if (tag) {
//PostAction(tag, "click")
}
}))
}
});
Edited-
Attaching both js files. it is working at my end.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
apiKey: "your api key",
authDomain: "you firebase domain",
databaseURL: "your firbase db url",
projectId: "your project id",
storageBucket: "",
messagingSenderId: "sender id"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = payload.data.Title;
var notificationOptions = {
body: payload.data.Body,
icon: payload.data.Icon,
image: payload.data.Image,
action: payload.data.ClickAction
};
console.log("strated sending msg" + notificationOptions);
return self.registration.showNotification(notificationTitle,notificationOptions);
});
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event.notification);
event.notification.close();
var redirectUrl = null;
if (event.notification.data) {
if (event.notification.data.FCM_MSG) {
redirectUrl = event.notification.data.FCM_MSG.data ? event.notification.data.FCM_MSG.data.click_action : null
} else {
redirectUrl = event.notification.data ? event.notification.data.click_action : null
}
}
console.log("redirect url is : " + redirectUrl);
if (redirectUrl) {
event.waitUntil(async function () {
var allClients = await clients.matchAll({
includeUncontrolled: true
});
var chatClient;
for (var i = 0; i < allClients.length; i++) {
var client = allClients[i];
if (client['url'].indexOf(redirectUrl) >= 0) {
client.focus();
chatClient = client;
break;
}
}
if (chatClient == null || chatClient == 'undefined') {
chatClient = clients.openWindow(redirectUrl);
return chatClient;
}
}());
}
});
self.addEventListener("notificationclose", function (event) {
event.notification.close();
console.log('user has clicked notification close');
});
application.js file :
/// <reference path="scripts/jquery-3.3.1.js" />
try {
var config = {
apiKey: "your api key",
authDomain: "you firebase domain",
databaseURL: "your firbase db url",
projectId: "your project id",
storageBucket: "",
messagingSenderId: "sender id"
};
firebase.initializeApp(config);
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker
.register('/firebase-messaging-sw.js')
.then((swReg) => {
firebase.messaging().useServiceWorker(swReg);
askForPermissioToReceiveNotifications();
})
.catch(function (error) {
console.error('Service Worker Error', error);
window.alert("Service Worker Error" + error);
})
} else {
console.warn('Push messaging is not supported');
window.alert("Push messaging is not supported " + (navigator.serviceWorker));
}
const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
console.log(messaging);
await messaging.requestPermission();
const token = await messaging.getToken();
if (token !== null || token !== 'undefined') {
await sendDeviceTokenToServerSide(token);
}
console.log('Got token : ' + token);
messaging.onMessage(function (payload) {
console.log('onMessage: ', payload);
setTimeout(() => {
navigator.serviceWorker.ready.then(function (registration) {
var notificationTitle = payload.notification.title;
var notificationOptions = {
body: payload.notification.body,
data: payload.data,
icon: payload.notification.icon,
image: payload.data.Image,
requireInteraction: payload.notification.requireInteraction,
tag: payload.notification.tag,
click_action: payload.data.click_action,
requireInteraction: true
};
registration.showNotification(notificationTitle, notificationOptions);
},50)
});
});
}
catch (e) { console.log('error in getting token: ' + e); window.alert("error in getting token: " + e); }
}
function sendDeviceTokenToServerSide(token) {
$.ajax({
type: 'POST',
url: '/Home/StoreToken',
timeout: 5000000,
data: { token: token },
success: function (success) {
console.log("device token is sent to server");
},
error: function (error) {
console.log("device error sending token to server : " + error);
window.alert("device error sending token to server : " + error);
}
});
}
} catch (e) {
window.alert("error: " + e);
}
function GetFcmUserToken(messaging) {
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
return refreshedToken;
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
}
self.addEventListener('notificationclick', function (event) {
const clickedNotification = event.notification;
// Do something as the result of the notification click
const promiseChain = clients.openWindow(clickedNotification.data.Url);
event.waitUntil(promiseChain);
});
This code inside service worker js worked fine for me on chrome Desktop and Android.

nativescript-background-http issue

I tried implementing image upload page for my app, but unfortunately the request is not reaching the server. I double checked this using tcpdump on the server side. The code doesnt seem to process beyond session.uploadFile in sendImages function
Please let me know if there is any issue with the code
var imageSource = require("image-source");
var frameModule = require("ui/frame");
var Observable = require("data/observable").Observable;
var fromObject = require("data/observable").fromObject;
var ObservableArray = require("data/observable-array").ObservableArray;
var platformModule = require("platform");
var permissions = require("nativescript-permissions");
var imagepickerModule = require("nativescript-imagepicker");
var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");
var fs = require("file-system");
var page;
var imageName;
var counter = 0;
function pageLoaded(args) {
page = args.object;
}
function onSelectSingleTap(args) {
var context = imagepickerModule.create({
mode: "single"
});
if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
.then(function () {
console.log("Permissions granted!");
startSelection(context);
})
.catch(function () {
console.log("Uh oh, no permissions - plan B time!");
});
} else {
startSelection(context);
}
}
function sendImages(uri, fileUri) {
imageName = extractImageName(fileUri);
var request = {
url: "http://maskingIpForPost:8081/mobilepic/ctk/uploadpic",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"file-Name": imageName,
"uid": 30
},
description: "{ 'uploading': " + imageName + " }"
};
var task = session.uploadFile(fileUri, request);
task.on("progress", progress);
task.on("error", error);
task.on("complete", complete);
task.on("responded", responded);
function responded(e) {
console.log("eventName: " + e.eventName);
console.log("data: " + e.data);
}
function progress(e) {
console.log("currentBytes: " + e.currentBytes);
console.log("totalBytes: " + e.totalBytes);
console.log("eventName: " + e.eventName);
}
function error(e) {
console.log("eventName: " + e.eventName);
console.log("eventName: " + e.responseCode);
console.log("eventName: " + e.response);
}
function complete(e) {
console.log("eventName: " + e.eventName);
console.log("response: " + e.responseCode);
}
return task;
}
function startSelection(context) {
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected_item) {
var localPath = null;
if (platformModule.device.os === "Android") {
localPath = selected_item._android;
} else {
// selected_item.ios for iOS is PHAsset and not path - so we are creating own path
let folder = fs.knownFolders.documents();
let path = fs.path.join(folder.path, "Test" + counter + ".png");
//let saved = imagesource.saveToFile(path, "png");
localPath = path;
}
alert("final path " + localPath);
if (localPath) {
var task = sendImages("Image" + counter + ".png", localPath);
//mainViewModel.get("items").push(fromObject({ thumb: imagesource, uri: "Image" + counter + ".png", uploadTask: task }));
}
counter++;
});
}).catch(function (e) {
console.log(e.eventName);
});
}
function extractImageName(fileUri) {
var pattern = /[^/]*$/;
var imageName = fileUri.match(pattern);
return imageName;
}
exports.pageLoaded = pageLoaded;
exports.onSelectSingleTap = onSelectSingleTap;
On Further research found the following
net.gotev.uploadservice.UploadService is undefined in background-http.android.js. At this moment i am not sure what this means. Would appreciate if anyone has idea about this
You need to change the following line in your code.
var session = bghttpModule.session("image-upload");
It has to be file upload
var session = bghttpModule.session("file-upload");
Just tested your code by using Azure Blob Storage PUT url at my side and got the below response.
ActivityManager: START u0 {act=android.intent.action.OPEN_DOCUMENT typ=image/* cmp=com.android.documentsui/.DocumentsActivity (has extras)} from pid 2835
JS: currentBytes: 4096
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: eventName: responded
JS: data:
JS: eventName: complete
JS: response: 201
thanks for the quick response, i tried running it on a emulator and i faced the above mentioned issue, i tried the same by connecting a device and it worked just fine.

AJAX error return ModelState Error

On my Create page I am using ajax and calling my api controller when creating a person:
<script>
$(document).ready(function() {
var newUrl = '#Url.Action("Index", "PersonInformations")';
var settings = {};
settings.baseUri = '#Request.ApplicationPath';
var infoGetUrl = "";
if (settings.baseUri === "/ProjectNameOnServer") {
infoGetUrl = settings.baseUri + "/api/personinformations/";
} else {
infoGetUrl = settings.baseUri + "api/personinformations/";
}
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
//console.log(jqXHR.responseText);
toastr.error(status + " - " + error.message);
}
});
}
});
});
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
});
</script>
Here is the method in my PersonInformations API controller:
[ResponseType(typeof(PersonInformation))]
public IHttpActionResult PostPersonInformation(PersonInformation personInformation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var lstOfPersons = db.PersonInformations.Where(x => x.deleted == false).ToList();
if (lstOfPersons.Any(
x =>
x.FirstName == personInformation.FirstName && x.LastName == personInformation.LastName &&
x.AId == personInformation.AgencyId && x.ID != personInformation.ID))
{
ModelState.AddModelError("", "This person already exists!");
return BadRequest(ModelState);
}
if (
lstOfPersons.Any(
x => x.Email.ToLower() == personInformation.Email.ToLower() && x.ID != personInformation.ID))
{
ModelState.AddModelError(personInformation.Email, "This email already exists!");
return BadRequest(ModelState);
}
personInformation.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.FirstName);
personInformation.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.LastName);
db.PersonInformation.Add(personInformation);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = personInformation.ID }, personInformation);
}
Now when I test this and purposely enter an email that already exists, the ajax request errors out but returns the message:
Error - The Request is invalid
but when I use console.log(jqXHR.responseText)
I get this:
Create
{
"$id": "1",
"message": "The request is invalid.",
"modelState": {
"$id": "2",
"test#test.com": [
"This email already exists!"
]
}
}
How do I get the "This email already exists!" as the error message?
I just figured this out. I know that the modelState was an array type, and the 2nd value was the actual email address entered.
So I edited my button.click event to this:
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
var emailValue = $("#Email").val();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
toastr.error(status + " - " + error.modelState[emailValue]);
}
});
}
});
});
Find the error message via array bracket notation along with getting the actual value of the email trying to be submitted did the trick.

Parse cloud code afterSave gets triggered twice

I have a aftersave on Parse cloud code. I have made changes to the table once but the aftersave hook triggers twice
1st Update (Actual update)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:37.733Z"}}
2nd Update (Shouldn't happen)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:38.038Z"}}
The only difference between the two updates is the updatedAt time. Will aftersave be triggered even if the update time changes?
How can I avoid the second aftersave execution?
Here is my cloud code :
Parse.Cloud.afterSave("Photos", function (request) {
var albumNameA = "";
var publicUser = "";
var albumOwner = "";
var photoUniqueId = "";
var isApproved = "";
albumNameA = request.object.get("albumTitle");
publicUser = request.object.get("addedBy");
photoUniqueId = request.object.id;
isApproved = request.object.get("approved");
if (request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime()) {
var getAlbumOwner = new Parse.Object.extend("Albums");
var q3 = new Parse.Query(getAlbumOwner);
q3.equalTo("title", albumNameA);
q3.first({
success: function (results) {
console.log("Checking for Creator name " + results.get("creatorName"));
albumOwner = results.get("creatorName");
console.log("Uploading a Photo Final " + albumNameA + "-by-" + publicUser + "--ownedby--" + albumOwner);
console.log("Uploading a Photo" + albumNameA + "-by-" + publicUser + "--" + photoUniqueId + "--" + isApproved);
var install = new Parse.Object.extend("Installation");
var q2 = new Parse.Query(install);
q2.equalTo("privacy", privateUserNo);
q2.equalTo("username", albumOwner);
q2.find({
success: function (results) {
if (!isApproved) {
Parse.Push.send({
where: q2, // Set our Installation query
data: {
alert: "New Photo uploaded by " + publicUser + " ,waiting for approval"
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
}
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
} else if (!(request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime())) {
console.log("all case scenarios");
var getAlbumOwner1 = new Parse.Object.extend("Albums");
var q6 = new Parse.Query(getAlbumOwner1);
q6.equalTo("title", albumNameA);
q6.first({
success: function (results) {
albumOwner = results.get("creatorName");
var sendApproval = new Parse.Object.extend("Photos");
var q4 = new Parse.Query(sendApproval);
q4.descending("updatedAt");
q4.first({
success: function (results) {
var objectIDNeeded = results.id;
var isChanged = results.get("approved");
var currentUpdateTime = results.get("updatedTime");
console.log("Your Photo, " + publicUser + " ,has been approved by " + albumOwner);
var install = new Parse.Object.extend("Installation");
var q5 = new Parse.Query(install);
q5.equalTo("privacy", privateUserNo);
q5.equalTo("username", publicUser);
q5.find({
success: function (results) {
Parse.Push.send({
where: q5, // Set our Installation query
data: {
alert: "Your Photo has been approved by " + albumOwner
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
});

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

Resources