Error: The 'then' method cannot be invoked on an undefined object in the Parse.File.save function

I am currently utilizing the Javascript API for parse.com within an Angular JS application. My goal is to successfully save or update the user's profile picture. Below is the code snippet that I have been working with:

Some HTML . . .

<input type="file" capture="camera" accept="image/*" id="profilePhotoFileUpload">

Credit goes to Google I/O, Raymond, and the Parse JS guide.

Here is the controller code snippet:

$scope.updateUserProfile = function (user) {

        var fileUploadControl = $("#profilePhotoFileUpload")[0];
        if (fileUploadControl.files.length > 0) {
            var file = fileUploadControl.files[0];
            var name = "photo.jpg";

            var parseFile = new Parse.File(name, file);

            parseFile.save();


}

An error keeps popping up:

TypeError: Cannot call method 'then' of undefined at Object.Parse.File.save (parse-1.2.8.js:4084:43)

It occurs when trying to execute parseFile.save()

Essentially, the _source is appearing as undefined . . . Any ideas why?

Thank you!

Answer №1

After working around it, I finally achieved my ultimate goal of using it with phonegap, thanks to the information provided in this post by Raymond Camden!

Here is a snippet of the code:

window.resolveLocalFileSystemURI(data, function(entry) {

    var reader = new FileReader();

    reader.onloadend = function(evt) {
        var byteArray = new Uint8Array(evt.target.result);
        var output = new Array( byteArray.length );
        var i = 0;
        var n = output.length;
        while( i < n ) {
            output[i] = byteArray[i];
            i++;
        }                
        var parseFile = new Parse.File("mypic.jpg", output);

        parseFile.save().then(function(ob) {
                navigator.notification.alert("Got it!", null);
                console.log(JSON.stringify(ob));
            }, function(error) {
                console.log("Error");
                console.log(error);
            });

    }

    reader.onerror = function(evt) {
          console.log('read error');
          console.log(JSON.stringify(evt));
      }

    entry.file(function(s) {
        reader.readAsArrayBuffer(s);
    }, function(e) {
        console.log('ee');
    });

});

}

Answer №2

For those working with Phonegap and Parse, Raymond Camden offers a helpful example for taking pictures:

http://www.raymondcamden.com/2013/07/23/better-example-of-phonegap-parse-and-uploading-fi...

var imagedata = "";    

$("#takePicBtn").on("click", function(e) {
    e.preventDefault();
    navigator.camera.getPicture(gotPic, failHandler, 
        {quality:50, destinationType:navigator.camera.DestinationType.DATA_URL,
         sourceType:navigator.camera.PictureSourceType.PHOTOLIBRARY});
});

function gotPic(data) {
    console.log('got here');
    imagedata = data;
    $("#takePicBtn").text("Picture Taken!").button("refresh");
}

The image is saved as follows:

var parseFile = new Parse.File("mypic.jpg", {base64:imagedata});
        console.log(parseFile);
            parseFile.save().then(function() {
                var note = new NoteOb();
                note.set("text",noteText);
                note.set("picture",parseFile);
                note.save(null, {
                    success:function(ob) {
                        $.mobile.changePage("#home");
                    }, error:function(e) {
                        console.log("Oh crap", e);
                    }
                });
                cleanUp();
            }, function(error) {
                console.log("Error");
                console.log(error);
            });

Pay attention to {base64:imagedata}, which is essential for creating the parse file using string data.

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

Getting the Promise Result from an AngularJS Service back to the Controller

itemsService includes an additem function that checks if the promise is successful in adding an item to the items array and passing it to the shoppinglist controller. Now, I also want to store the promise result and pass it to the controller in list.stat ...

Is it possible to utilize a CSV file to dictate which images should be utilized on my website as a guide?

I'm currently working on my website's gallery and have a collection of over 60 images. I'm exploring ways to streamline the process of displaying these images by having the website read their names from a CSV file instead of manually coding ...

There seems to be a problem with the output when trying to display the message "You said ${reply}"

In the following code snippet, vanilla.js is being used with ATOM as the text editor and running on nodejs via terminal: 'use strict'; const Readline = require('readline'); const rl = Readline.createInterface({ input:process.stdin, ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

What do you notice about interactions involving 'input type=text' in HTML and JavaScript?

When a new binding is created for the value property on an input, any manual modifications by the user no longer update the value. What happens when the binding is altered? Does regular user interaction involve key press listeners? I've modified the ...

How can a functional component be created in VueJS using x-templates?

Looking to create a functional component in VueJS with a template as a single-file component? Utilizing x-templates means your component will be stored in a .html file. Want to transform the given component into a functional component? <!-- my_compone ...

The jQuery plugin functions smoothly when running on localhost, but it causes issues with the background image when deployed on the web

I created a compact plugin to show a cookie message. While testing it on my local machine, everything functioned smoothly without affecting any web pages. However, once I transferred the files to the server, I encountered issues such as: A background ima ...

What is the secret to creating a button that can sort text and another button that flips the word density in my content?

I'm not a fan of having something like this because it's displeasing to the eye: https://i.stack.imgur.com/3F4sp.jpg Instead, I prefer my word density to be more organized and structured. How can I achieve this? Sort by highest word density fi ...

Angular threw an error stating that it encountered an unexpected token 'var' when trying to declare a variable x as

Currently facing a challenge with my Angular application development. I have created a TS File that interacts with my API (imported in the index.html using a script tag) and exported some functions from this file to be used in my components. Despite everyt ...

Trouble with refreshing view - angular, firebase

I've been struggling with getting this function to fire more than once, even though it should update when scope.job.getApplicants() changes. I've tried various methods like $watch, $apply, and firebase's ref.on('value', but nothing ...

Unusual host value being returned by next/headers in Next.js version 13

In my current Next.js project, I am utilizing next/headers to dynamically set a baseUrl for calls to my API. const baseUrl = () => { const protocol = process?.env.NODE_ENV === "development" ? "http" : "https"; const ...

Leveraging PHP JSON responses for decision-making in jQuery/JavaScript

Recently, a friend shared the following code snippet with me: json : { result: true } success function(data){ if(data.result) { //do something here } else { //do something here } } I'm curious how I can integrate that ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

Steps for launching a browser using Capybara and Selenium

I am completely new to utilizing Capybara and have not had any experience with Selenium in the past. Currently, I am working on a Ruby on Rails project on MacOSX and encountering an issue where the browser window does not open when I execute my test. My te ...

Utilize the key-value pair from ng-repeat to expand the scope of the expression

In an attempt to utilize the key value from ng-repeat as an extension of another scope.arrayResult, I aim to achieve arrayResult.q1/q2/q3 etc... <ul ng-repeat="(key,x) in data"> <li><h4>Question: {{x}}</h4> <p>{{ ar ...

Having trouble setting up jQuery UI Datepicker in my system

I am attempting to add a datepicker to my website, but it is not showing up in the browser. Could there be an issue with some of the other script files I have? Below is where my datepicker div is located: <body> <!-- Preloader --> <div id= ...

ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another fil ...

Using ThreeJS to project a mouse click onto the XZ plane

I am currently working on implementing offline routing in a 3D map within a ThreeJS scene. My goal is to allow the user to click on a point and have a cube navigate to that point. While the navigation functionality is working correctly, I am facing an issu ...

Can the garbage collector in Typescript/JavaScript effectively handle circular references, or does it result in memory leaks?

When working in languages such as C#, managing memory is not a problem. However, this can lead to difficult-to-find memory bugs in other languages. Is it safe to use the following code snippet in Typescript or Javascript without encountering any issues? c ...

Invisible enigmatic anomaly detected on non-existent line within the realm of Node.js

Today, when I tried to run my app on node, it encountered an unexpected token error at line 219 in the file. The full error log is as follows: syberic@syberic:~/Web/lotalot$ node app.js /home/syberic/Web/lotalot/config/passport.js:219 }); ^ SyntaxError: ...