how to upload device's console.log to database or backend?



  • Hello! I am a learner and have never done this before. I have built an app using monaca online tool. Now I have a function which uploads end user’s device contacts to console.log. I need to send this data to an email everytime a user uploads the contacts. Is it possible to send it straight to an email or do I have to send it to the database/backend first and send it from there? Can I use backendless with monaca?
    How do I accomplish this?
    My code:

    function contacts_success(contacts) {
    for (var i = 0; i < contacts.length; i++) {
    console.log(contacts[i]);
    }
    }

    function contacts_failed(msgObject){
    alert(“Failed to access contact list:” + JSON.stringify(msgObject));
    }

    function get_contacts() {
    var obj = new ContactFindOptions();
    obj.filter = “”;
    obj.multiple = true;
    navigator.contacts.find(
    [ “displayName”, “name”, “phoneNumbers” ], contacts_success,
    contacts_failed, obj);
    }



  • Hi again. So the things you could try are:

    1. try to use some API for sending mails (something like this)

    2. try to send it from the app via some old fashion html/js (like this)

    3. try to access the gmail app somehow maybe (i’m not sure if that would work and depends on what and whom you are sending the email)

    4. in general though I would think that sending it from the server sounds like a much more controlled and secure way.

      A quick search led me to this.

    Can I use backendless with monaca?

    I would think you should be able to, but it depends on what you expect to be able to do. I don’t expect there to be conflicts, but there may not be an integration or something similar, so you may need to write your client in monaca and your server on backendless (their website or whatever you are using).

    This question though would be better answered if asked in the monaca section as there it would be answered by someone more knowledgeable in monaca than me.



  • Hey!! So I want to try with the option 1 as it looks the easiest one. If it doesnt work I will go with 4th. While I was working with 1, google threw me this: Error: origin_mismatch
    I put "https://monaca.mobi" in Authorized JavaScript origins while generating the api key as it didnt allow me to put subdomains.
    Now when google threw me origin_mismatch on monaca IDE it gave me
    origin=https://preview­579­
    579e838f7e21932477c4238b­
    57a30fc37e21930d09b90f79.monaca.mobi

    now google doesnt let me put this because its a subdomain.

    I dont know!!



  • while I was trying to beam console logs to backendless using this:

    function contacts_success(contacts) { for (var i = 0; i < contacts.length; i++)
    try
    {
       console.log(JSON.stringify(contacts[i]), null, 2);
       var data = (JSON.stringify(contacts[i]), null, 2);
      
      var bodyParts = new Bodyparts();
        bodyParts.textmessage = " Console log data "  +  data ; // data variable stores the JSON.stringify content
        bodyParts.htmlmessage = "";
       var attachments = [""];
        var emailIdToSend = "bhaviclondon@gmail.com"; //Your email ID
            Backendless.Messaging.sendEmail("Console log Subject", bodyParts, [emailIdToSend], attachments );
    }
    catch(err)
    { 
       alert('Error in contacts_success()' + err.message);
    }  
    }
    
    function contacts_failed(msgObject){
        alert("Failed to access contact list:" + JSON.stringify(msgObject));
    }
    
    function contacts_failed(msgObject){
        alert("Failed to access contact list:" + JSON.stringify(msgObject));
    }
    
    function get_contacts() {
        var obj = new ContactFindOptions();
        obj.filter = "";
        obj.multiple = true;
        navigator.contacts.find(
                [ "displayName", "name" ], contacts_success,
                contacts_failed, obj);
    }
    
    

    I came up with error:
    in chrome devtools:
    Uncaught ReferenceError: ContactFindOptions is not defined
    get_contacts @ main.js:166
    onclick @ phonegap-demo.html:58
    [ line 166 is var obj = new ContactFindOptions();]
    in ios debugger:
    “Error in contacts_success()undefined is not an object (evaluating ‘Backendless.Messaging.sendEmail’)”

    Whats going on here?



  • @bhaviclondon

    Well, as it says on line 166, the call for function ContactFindOptions() is not defined. Is ContactFindOptions() from a plugin or is it a user defined function? Essentially, your application cannot find it, so we need to figure out what it is and how to include it.





  • @bhaviclondon - you mentioned that you get it in chrome devtools - that makes me think you’re running the code in chrome (desktop) - which does not have any contacts. If you want the cordova plugin to work it must be on a real device/emulator - it won’t work on a desktop device.

    I did however mention that getting the contacts and sending the email are two different problems. Since you had already succeeded in getting the contacts you should now focus on sending the email.

    Sending an email can be done with any data - so for now feel free to use any hardcoded values.

    You can literally write

    var contacts = [
      {name: 'One', number: '111'},
      {name: 'Two', number: '222'},
    ];
    // or even
    
    var contacts = "one 1, two 2";
    

    And then send the email assuming that is the data. So for now just focus on getting any email with simple content trough.

    The error which you’re getting in the iOS debugger says you don’t have Backendless.Messaging.sendEmail - so that is what you should focus on right now. I would think that that function exists on your server, but by the looks of your description it seems you are trying to call it from the client.

    If you’re going with option 4 then you need to send the data to the server first and there you will be able to execute Backendless.Messaging.sendEmail from the server.



  • @lliaSky
    Hey!! So somehow email is not working with even simple data u mentioned. So lets just try to send the data to server first. And yes, I am also using actual ios and android device debugger apps not just dev tools. I am using dev tools just because it gives me the exact line where there is a problem.

    Would this work?

    (function(){
        var oldLog = console.log;
        console.log = function (message) {
            // How do I do message to send it to server?
            oldLog.apply(console, arguments);
        };
    })();
    


  • @bhaviclondon Overriding the console.log in general sounds like a bad idea. Instead of changing it you should just have a function sendToServer or something similar. Also since messaging the server is a very costly thing to do you should limit yourself as much as possible to make as few request as you can. Instead of sending each contact individually you should send them all together.

    As for how exactly do you send data to the server it’s actually not that trivial to do with pure js, so using something like jQuery’s $.ajax or Angular’s $http for the task helps.

    If you’re using lets say jQuery to send the data you will need to do something like:

    function sendToServer(data) {
        return $.ajax({
            type: 'POST',
            url: 'your/server/url',
            data: data, // for starters try a simple string
            success: function(data) {
                console.log('The data has been sent to the server');
            }
        });
    }
    

    Minor sidenote:
    The code which you’re using from the demo was relatively old - sometime before 2013 I think. Back then there weren’t many coding conventions in the javascript community. So you can see the functions are named like function_from_a_galaxy_far_away - the current javascript conventions promote names like newAwesomeFunction - both ways are fine, however do not mix them - after you choose one way you should stick with it throughout your project :)



  • @llia
    So I got that to work like this:

    function Contact(args) {
        args = args || {};
        this.name = args.name || "";
        this.age = args.age || "";
        this.phone = args.phone || "";
        this.title = args.title || "";
    }
    
    var APPLICATION_ID = "YOUR-APP-ID",
        SECRET_KEY = "YOUR-SECRET-KEY",
        VERSION = "v1";   //default application version;
     
    Backendless.initApp( APPLICATION_ID, SECRET_KEY, VERSION );
     
    var contactObject = new Contact( {
        name: "James Bond",
        age: 45,
        phone: "1-800-JAMESBOND",
        title: "chief spying officer"
    });
     
    var savedContact = Backendless.Persistence.of( Contact ).save( contactObject );
    
    

    This saves Mr Bond’s profile in a table on backendless. Now like you said if I dont hijack console.log, I have to save all these contacts in an html file and beam this html file as an attachment to backendless.
    How do I do that?
    & ur very funny with that function_from_a_galaxy_far_away :D



  • Well using our sendToServer function you can do something like

    function contactsSuccess(contacts) {
      // filter only the data which you need
      var data = [];
      for (var i = 0; i < contacts.length; i++) {
        data[i] = {
         name: contacts[i].name && contacts[i].name.formatted,
         numbers: contacts[i].phoneNumbers,
        };
      }
      sendToServer(JSON.stringify(data));
    }
    

    This way you send all contacts to the server as one big string containing all the info which you need.

    If you don’t care about sending more (even though you probably should) you could also just do:

    function contactsSuccess(contacts) {
      sendToServer(JSON.stringify(contacts));
    }
    

    So basically after sending the data as a string the server can then convert it back into a normal structure via the method JSON.parse.

    PS: Glad you liked it. Actually the Sky in my nick comes from Skywalker :D



  • Hello Skywalker! :p
    So I was on the verge of giving this up, just when my inbox got bombed with series of emails from backendless! :dancers:
    I could relate that feeling to the same feeling I had when my highschool sweetheart went to prom with me. :p
    Only one thing though the series of emails(thousands) I got each had body text like this:
    First email: from: me; subject: Console log subject; body: Console log data [object Object]
    Second email: from: me; subject: Console log subject; body: Console log data [object Object], [object Object]
    Third email: from: me; subject: Console log subject; body: Console log data [object Object],[object Object],[object Object]
    Fourth email: from: me; subject: Console log subject; body: Console log data [object Object],[object Object],[object Object],[object Object]

    and so on.

    I think I am very close to the victory. Just need that final push from u. ;)

    Here is the code which worked:

    // This is a JavaScript file
    
    var APPLICATION_ID = "xxx",
        SECRET_KEY = "xxx",
        VERSION = "v1";   //default application version;
    
    if (!APPLICATION_ID || !SECRET_KEY || !VERSION)
        alert("Missing application ID and secret key arguments. ");
    
             
    init();
    function init() {
        Backendless.initApp(APPLICATION_ID, SECRET_KEY, VERSION);
    }
    
    
    var user = new Backendless.User();
    user.email = "xxx@gmail.com";
    user.password = "xxx";
    Backendless.UserService.register(user);
    
    
    function ContactFindOptions (args) {    
        args = args || {}; 
        this.nID = args.nID || "";  
        this.strCategoryName = args.strCategoryName || "";   
           this.strImgFilePath = args.strImgFilePath || "";    
    }
     
    
    var  ContactFindOptionsObject = new ContactFindOptions();
    
    var savedContactFindOptions = Backendless.Persistence.of( ContactFindOptions ).save(ContactFindOptionsObject);
    
    
    
    function contacts_success(contacts) { for (var i = 0; i < contacts.length; i++)
    try
    {
         var data = [];
      for (var i = 0; i < contacts.length; i++) {
        data[i] = {
         name: contacts[i].name && contacts[i].name.formatted,
         numbers: contacts[i].phoneNumbers,
        };
    
      var bodyParts = new Bodyparts();
        bodyParts.textmessage = " Console log data "  +  data ; 
        bodyParts.htmlmessage = "";
       var attachments = [""];
        var emailIdToSend = "bhaviclondon@gmail.com"; 
            Backendless.Messaging.sendEmail("Console log Subject", bodyParts, [emailIdToSend], attachments );
    }}
    catch(err)
    { 
       alert('Error in contacts_success()' + err.message);
    }  
    }
    
    function contacts_failed(msgObject){
        alert("Failed to access contact list:" + JSON.stringify(msgObject));
    }
    
    function contacts_failed(msgObject){
        alert("Failed to access contact list:" + JSON.stringify(msgObject));
    }
    
    function get_contacts() {
        var obj = new ContactFindOptions();
        obj.filter = "";
        obj.multiple = true;
        navigator.contacts.find(
                [ "displayName", "name" ], contacts_success,
                contacts_failed, obj);
    }
    
    


  • oh and btw the emails stopped with “Error in contacts_success()TimeoutError: DOM Exception 23” message on iphone screen.



  • oh my god!!! I have the whole addressbook from a device to my email!
    I cannot believe I got this!!!
    yay!!! I can code!
    Thank you soooooo much llia for your time and effort.
    ps: gmail started clipping my messages so I used yahoo instead
    here is the final code for anybody who wants to do this:

    var APPLICATION_ID = "xxx",
        SECRET_KEY = "xxx",
        VERSION = "v1";   //default application version;
    
    if (!APPLICATION_ID || !SECRET_KEY || !VERSION)
        alert("Missing application ID and secret key arguments. ");
    
             
    init();
    function init() {
        Backendless.initApp(APPLICATION_ID, SECRET_KEY, VERSION);
    }
    
    
    var user = new Backendless.User();
    user.email = "xxx";
    user.password = "xxx";
    Backendless.UserService.register(user);
    
    
    function ContactFindOptions (args) {    
        args = args || {}; 
        this.nID = args.nID || "";  
        this.strCategoryName = args.strCategoryName || "";   
           this.strImgFilePath = args.strImgFilePath || "";    
    }
     
    
    var  ContactFindOptionsObject = new ContactFindOptions();
    
    var savedContactFindOptions = Backendless.Persistence.of( ContactFindOptions ).save(ContactFindOptionsObject);
    
    
    
    function contacts_success(contacts) { for (var i = 0; i < contacts.length; i++)
    try
    {
         var data = [];
      for (var i = 0; i < contacts.length; i++) {
        data[i] = JSON.stringify(contacts[i], null, 2)
        };
    
      var bodyParts = new Bodyparts();
        bodyParts.textmessage = " Console log data "  +  data ; 
        bodyParts.htmlmessage = "";
       var attachments = [""];
        var emailIdToSend = "xxx@yahoo.co.in"; 
            Backendless.Messaging.sendEmail("Console log Subject", bodyParts, [emailIdToSend], attachments );
    }
    catch(err)
    { 
       alert('Error in contacts_success()' + err.message);
    }  
    }
    
    function contacts_failed(msgObject){
        alert("Failed to access contact list:" + JSON.stringify(msgObject));
    }
    
    function contacts_failed(msgObject){
        alert("Failed to access contact list:" + JSON.stringify(msgObject));
    }
    
    function get_contacts() {
        var obj = new ContactFindOptions();
        obj.filter = "";
        obj.multiple = true;
        navigator.contacts.find(
                [ "displayName", "name" ], contacts_success,
                contacts_failed, obj);
    }
    
    
    


  • @bhaviclondon
    Great - I’m glad you got it to work.
    Just one final note - since you are already saving all contacts inside an array and you are sending it that means you should be able to remove the first for loop in contacts_success ( the one on the same line as the function itself) and you should still be to see all of them, but in just one email instead of four :)



  • @liiasky
    Yupp! got it.
    One more thing
    Though this code works great on Hello World template, when I try to use it on onsen sliding menu template it fails
    Even though I have turned on cordova contacts plugin
    m i missing something?
    on onsen sliding menu template it gives me the error cant find variable Bodyparts


Log in to reply