Getting files onto your device - the Phonegap way

I'm having trouble exporting or downloading information to a file. It works fine in my browser, but when I try it in my phonegap app, the file just opens as text without an option to save it or return to the app. Any advice? Keep in mind that I'm not very experienced with JavaScript - more of a beginner!

    function dbError(e) {
        console.log("SQL ERROR");
        console.dir(e);
    }

    function backup(table) {
    var def = new $.Deferred();
    curatio.webdb.db.readTransaction(function(tx) {
        tx.executeSql("select * from "+table, [], function(tx,results) {
            var data = convertResults(results);
            console.dir(data);
            def.resolve(data);
        });
    }, dbError);

    return def;
}

$(document).on("click", "#doBackupBtn", function(e) {
    e.preventDefault();
    console.log("Begin backup process");

    $.when(
        backup("allergies")

    ).then(function(allergies, log) {
        console.log("All done");
        var data = {allergies:allergies}
        var serializedData = JSON.stringify((data), null, 4);
        console.log(serializedData);
        download("Export.csv", serializedData); 

        (function(console){

console.save = function(data, filename){

    if(!data) {
        console.error('Console.save: No data')
        return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
        data = JSON.stringify(data)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
 }
})(console)


    });

});


    function download(filename, content) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
    pom.setAttribute('download', filename);
    pom.click();
    }

    //Generic utility
function convertResults(resultset) {
    var results = [];
    for(var i=0,len=resultset.rows.length;i<len;i++) {
        var row = resultset.rows.item(i);
        var result = {};
        for(var key in row) {
            result[key] = row[key];
        }
        results.push(result);
    }
    return results;
}


        </script>

Answer №1

If I understand correctly, you're looking to transfer a database to a file.

I've created some code for this purpose on my GitHub Gist, and also detailed it in a corresponding blog post of mine. By customizing the SQL queries and attributes in the code provided, you can easily export your database data into a file using JSON format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for developing a versatile code for passport.authenticate

I have a scenario where multiple controllers contain various methods that require user authentication to access database data. I am currently attempting to streamline the authentication process to avoid repetition in my code. Within the controller: const ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

Is there a way to incorporate expandable content on a Drupal node page using Javascript?

Is there a Drupal Module available that can display a trimmed version of content on the node page and expand it when clicking on a "Read More" link? Thank you! ...

Passing a service into a directive results in an undefined value

Can someone help me understand why a service I am injecting into a directive is returning undefined in certain instances? If you would like to take a look at the code, here is a plunker link: https://plnkr.co/edit/H2x2z8ZW083NndFhiBvF?p=preview var app = ...

Guide on executing a function exclusively when the state of a service variable changes within an Angular4 component

In my InfoFormService, I have a variable called isInValidating that is initially set to false. This variable becomes true when the component calls the validateEmail(email) function as shown below. @Injectable() export class InfoFormService { private ...

Replacing default hover behavior from an external library

Currently, I am utilizing a JS library that comes with a specific widget. Basically, I have the following list (I removed unnecessary DOM code): <li class="disabled"> When I hover over this list item, it turns into: <li class="disabled state-a ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Output the following by using the given format: *a* -> *a1**aabbbaa* -> *a2b3a2*

I am a beginner in JavaScript. Could you please explain how to achieve the following output? * "a" -> "a1" * "aabbbaa" -> "a2b3a2" I attempted using a hash map, but my test cases are failing. Below is the code I have writt ...

The functionality of JQuery's `.on("click"... is sporadically functioning

I have a code block that dynamically generates elements and includes event handling. However, the event handling sometimes works and other times it doesn't. I'm not sure how to debug this issue. Can someone help me figure out what might be causin ...

Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it au ...

Verifying that the mapDispatchToProps functions have been triggered using ReactTestingLibrary

I am currently utilizing mapDispatchToProps to invoke a dispatch function that calls an API within the useEffect hook of my functional component. I am facing some challenges when attempting to write unit tests for this scenario using React Testing Library ...

Ways to enhance the value of an option within a drop-down menu in angular js 1.x and retrieve the selected value

Can someone help me convert this jQuery code to AngularJS 1.x? <select id="select"> <option value="1" data-foo="dogs">this</option> <option value="2" data-foo="cats">that</option> <option value="3" data-foo="gerbil ...

Issue with VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Is there a way to use nightwatch.js to scan an entire page for broken images?

Hi there, I'm currently working on creating a test to ensure that all images are loaded on a webpage with just one single test. I assumed this would be a straightforward task that many people have already done before, but unfortunately, I haven' ...

Using the `await` command may lead to the variable losing its scope

Utilizing the await keyword to retrieve data from the database has been causing me some trouble. The variable secuity_ok is set to true on one line, but inexplicably changes to false on the following line. What could be causing this issue? It's worth ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

Implementing line breaks in JSON responses in an MVC application

I am looking to show a JavaScript alert with line breaks using the message returned from a controller action that returns JSON result. I have included "\n" in the message for line breaks. Below is the code snippet from my controller: [HttpPost] publ ...

Efforts to toggle visibility of icons in React

One issue I encountered is with the Navbar in mobile mode, where the icons are covering the menu. Refer to the image for a visual representation of the problem. https://i.sstatic.net/7eNeg.png To address this issue, my plan is to hide the icons when the ...