Get additionalData from Onesignal (Phonegap) - javascript

I read the doc here : https://documentation.onesignal.com/docs/cordova-sdk but it's totally not clear !
I try severals test nothing, I event test to get the title but still nothing
document.addEventListener('deviceready', function () {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
alert('notificationCallback: ' + JSON.stringify(jsonData)); => json data
alert('Title : '+ JSON.stringify(jsonData.payload.title)); => nothing
alert('Title2 : '+ jsonData.payload.title); => nothing
alert('Additional data: '+ jsonData.payload.additionalData); => nothing
};
window.plugins.OneSignal
.startInit("MY_ID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
}, false);
How to retrieve this data..
Thanks

After multiple debugs on my app, I finally found the application. The JSON structure of jsonData is :
jsonData
notification: {
payload: {
title: "YOUR_TITLE",
body: "BODY",
additionalData: {
"YOUR_KEY" : "YOUR_VALUE"
},
So to retrieve your data :
JSON.stringify(jsonData.notification.payload.additionalData.<YOUR_KEY>)

Instead of jsonData.payload try with jsonData.OSNotificationPayload
Ex: to access title
jsonData.OSNotificationPayload.title

Related

AngularJS - Correctly formatting asynchronous calls

newbie here.
I am trying to understand how I need to structure asynchronous calls within my controller to fit my specific use case:
Consider the following code snippet from an Angular Module in "service.js" within my project:
function getSearchObjects(projectName, title) {
var payload = JSON.stringify({
"title": title
});
var request = $http({
method: 'post',
url: URL + '/search/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
};
function runQuery(projectName, fromDate, toDate, sort, direction, columns) {
var from = Date.parse(fromDate);
var to = Date.parse(toDate);
var payload = JSON.stringify({
"fromDate": from,
"toDate": to,
"sort": sort,
"direction": direction,
"columns": columns
});
console.log(payload);
var request = $http({
method: 'post',
url: URL + '/query/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
return response.data;
};
function handleError(response) {
if (!angular.isObject( response.data ) || !response.data.error) {
return( $q.reject( "An unknown error occurred." ) );
}
return $q.reject( response.data.error );
};
});
Within my controller, I am trying to troubleshoot the following function:
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date, objectProperties.sort, objectProperties.direction, objectProperties.columns)
},
function(error) {
console.log(error);
});
};
getSearchObjects matches a title ($scope.selected.search) selected in my UI and grabs the following more detailed object from an API call:
{ title: 'Duplication Example',
sort: '#_traac-timestamp',
direction: 'desc',
columns: [ '#_traac-remote_ip', 'c-platform-m-distinct-id_s', '_type' ] }
I am trying to grab the properties returned from getSearchObjects and pass them along with a few user selected values from my UI to runQuery, which then returns data from a database to the user, but when I check the values passed to runQuery using the above logic in my controller, I get the following values. All of the objectProperties values I am attempting to pass to runQuery are undefined:
project_name: "Example Project"
start_date: 1499770800000
end_date: 1499943600000
sort: undefined
direction: undefined
columns: undefined
I have been trying to debug this, but I am too new to using Angular and asynchronous calls to really understand what I am doing wrong. My best guess currently is that I am calling runQuery before the values retrieved from getSearchObjects are attached to objectProperties. Either that or I am incorrectly referencing the properties within the objectProperties variable.
Could someone help me troubleshoot this issue, and better understand what I am doing wrong?
Thank you in advance for your help!
When you do this:
var objectProperties = some async function...
You are assigning the promise of the async function to the variable, not the result of it.
The result is coming in the .then, like you declared:
.then(function(result) { ... }
So, instead of objectProperties.sort, objectProperties.direction, objectProperties.columns, try using result.sort, result.direction, result.columns :)
If you are new to Promises, take a look at this simple, but great tutorial.
EDIT
Based on your comment, you are receiving, inside the response.data, the following object:
{"objectMatch": {
"title": "doc-event",
"sort": "#_traac-timestam‌​p",
"direction": "desc‌​",
"columns": [
"m-doc-‌​name_s",
"m-user_s",
"‌​m-full-action-type_s‌​",
"m-event-action-de‌​scriptor_s"
]}
}
So you have: response > data > objectMatch > properties you want.
The response.data you are extracting on your handleSuccess function:
function handleSuccess(response) {
return response.data;
};
So here, your result is response.data, containing the property objectMatch.
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
...
},
...
If all of that is correct, you should be able to access the values you want using result.objectMatch.<sort, direction or columns>, like:
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date,
result.objectMatch.sort, result.objectMatch.direction, result.objectMatch.columns)

Parameters are not working in Google Cloud Print using Google Apps Script

I need to send print Job to my printer using Google Cloud Print. It is a Classic Printer Named RISO ComColor 7150. My Code in Apps Script is as follows:-
function printGoogleDocument(docID, printerID, docName , type , duplex) {
var ticket = {
version: "1.0",
print: {
color: {
type: type,
vendor_id: "Color"
},
duplex: {
type: duplex
}
}
};
var payload = {
"printerid" : printerID,
"title" : docName,
"content" : DriveApp.getFileById(docID).getBlob(),
"contentType": "application/pdf",
"ticket" : JSON.stringify(ticket),
"pages" : "1,2"
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
}
problem is When i am Sending type to STANDARD_COLOR and duplex to NO_DUPLEX than it is Working fine but when i change them to MONOCHROME and DUPLEX than it is Giving me Color print with no duplex again. Also i am Sending Page Number but it Prints whole pdf instead of giving me print of specific page.
Can Anybody tell me what i am doing worng here??
Thanks in Advance.
you can set all the things in print job ticket, no need to specify the page number outside ticket.
Here ,a CJT am recommending ,
var ticket = "{\"version\":\"1.0\",\"print\":{\"color\":{\"vendor_id\":\"1\",\"type\":1},\"duplex\":{\"type\":0},\"page_orientation\":{\"type\":"0"},\"copies\":{\"copies\": "2"},\"fit_to_page\":{\"type\":3},\"page_range\":{\"interval\":[{\"start\": "1",\"end\":"2"}]},\"media_size\":{\"width_microns\":210000,\"height_microns\":297000,\"is_continuous_feed\":false,\"vendor_id\":\"9\"},\"collate\":{\"collate\":false},\"reverse_order\":{\"reverse_order\":false}}}";
so you can specify duplex, page limit..etc
It would be nice if you can go this documentation.
https://developers.google.com/cloud-print/docs/cdd#pts
And for duplex,its an integer expecting, you can set this way..if NO_DUPLEX is needed you need to send 0,
NO_DUPLEX = 0;
LONG_EDGE = 1;
SHORT_EDGE = 2;

A Mystery in my Code

I have fixed the issue with ajax on typo3. Now comes another issue in hand. This time is related to returning the object found in the action to Javascript. So I tell you what I do exactly.
here is first my ajax call function:
function getContent(id)
{
console.log("Starting process ...");
$.ajax({
async: 'true',
url: 'index.php',
type: 'POST',
data: {
eID: "ajaxDispatcher",
request: {
pluginName: 'listapp',
controller: 'Pays',
action: 'getMyCompanys',
arguments: {
'id': id
}
}
},
dataType: "json",
success: function(result) {
var data = JSON.parse(result)
console.log(data.nom);
},
error: function(error) {
console.log(error);
}
});
}
and here is the "getMyCompanys" action:
public function getMyCompanysAction()
{
$argument = $this->request->getArguments('id');
$company = $this->entrepriseRepository->findBypays(2); // just to test with the id 2
$result = (array) $company;
return json_encode($result);
}
Now on the console I get this Output:
{"\u0000*\u0000dataMapper":{},"\u0000*\u0000persistenceManager":{},"\u0000*\u0000query":{},"\u0000*\u0000queryResult":null}
So at the first glance , i thought the object was not passed to the javascript , but when I tried to add an attribute to the object $company ($company->att = 'val';)
I get this output :
{"\u0000*\u0000dataMapper":{},"\u0000*\u0000persistenceManager":{},"\u0000*\u0000query":{},"\u0000*\u0000queryResult":null**,"att":"val"}**
notice that the added attribute and its value get showed
so I now I'm convinced that there is something wrong with the object. I am also 100 % sure that the method findBypays(2); is working, I tried it in a listAction.
I don't really know what could be the problem :/
Just for your Information: this is part of an extension in typo3 that I developed myself using JBuilder
well after struggling for a long time , I tried a trick and it worked and it proved me that the json_encode does not return an object in typo3 eventhough I applied the :
$object->toArray() or (array) $object
to the object , so my solution was :
$companies = array();
foreach ($this->adresseRepository->findByland($id) as $company)
{
$companies[] = array(
'uid' => $company->getUid(),
'firma' => $company->getFirma(),
'strasse' => $company->getStrasse(),
'plz' => $company->getPlz(),
'ort' => $company->getOrt(),
'land' => $company->getLand(),
'telefon' => $company->getTelefon(),
'email' => $company->getEmail(),
'webseite' => $company->getWebseite()
);
}
return json_encode($companies);
and It Worked ;)

Pass Javascript Array to Polymer 'post-service' html

I'm still new at Polymer and I'm slowly learning how to use Polymer by modifiying the examples that Google provided.
But I'm encountering a bit of an issue.
I have a Array in Javascript:
var dash = [{"uid": 1,
"text" : "It's a TOWN!",
"username" : "Sam112",
"avatar" : "../ToolKit/images/avatar-01.svg",
"favorite": false,
"num" : "Standard"}];
function addto ()
{
dash.push({"uid": 2,
"text" : "It's a BABY!",
"username" : "Pete223",
"avatar" : "../ToolKit/images/avatar-01.svg",
"favorite": false,
"num" : "Standard"});
}
And I want to put this data in the 'post-service' template file:
<script>
Polymer('post-service',
{
created: function()
{
this.posts = dash;
},
postsLoaded: function()
{
this.posts = this.$.ajax.response.slice(0);
},
setFavorite: function(uid, isFavorite)
{
console.log('Favorite changed: ' + uid + ", now: " + isFavorite);
}
});
</script>
So i called the addto() function and then I loaded the index.html Polymer file and i expected to load data from the Array...
But It loads the Array, but the added object ( from addto() ), doesn't load.
It apparently loads from the original array but not the new entry from the addto() function.
Is there a way to make 'post-service' load an array when it changes? Thanks again!
I think this is not working because dash is only assigned to this.posts in the created handler, so typically on construction of the polymer element. If you call addTo afterwards, it will change dash, but dash will never be assigned to this.posts again.
Maybe add the addTo function to the element itself? Like:
Polymer('post-service',
{
created: function()
{
this.posts = dash;
},
addTo: function(arr)
{
this.posts.push (arr)
},
postsLoaded: function()
{
this.posts = this.$.ajax.response.slice(0);
},
setFavorite: function(uid, isFavorite)
{
console.log('Favorite changed: ' + uid + ", now: " + isFavorite);
}
});
</script>
Thanks kroonwijk!
I eventually gave up and I just used local-storage and JSON's stringify and parse to transfer between the Polymer element and my Javascript Data.
localStorage["names"] = JSON.stringify(dash);
And on the Polymer Side...
Polymer('post-service',
{
created: function()
{
this.posts = JSON.parse(localStorage["names"]);
},
postsLoaded: function()
{
this.posts = this.$.ajax.response.slice(0);
},
setFavorite: function(uid, isFavorite)
{
console.log('Favorite changed: ' + uid + ", now: " + isFavorite);
}
});
Much easier, sorry IE 7 and lower...

jquery.couchdb.js Ajax success/error not being called

I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});

Categories