"Utilizing Angular's $http.post to extract data from resolved promises

Can you help me figure out how to successfully send data through $http.post that I receive from a function using $q.defer()? Here is the code snippet:

HTML

<input type='text' ng-model='name'/>
<input type='file' id='inputFile' />
<button ng-click='save'>Save</button>

JavaScript

file = document.getElementById('inputFile');

function imgToBase64(file_input) {
    var deferred = $q.defer();
    if (file_input.files && file_input.files[0]) {
        var fileReader = new FileReader();
        fileReader.onload = function (event) {
            result = event.target.result;
            deferred.resolve(result);
        };
        fileReader.readAsDataURL(file_input.files[0]);
    }
    return deferred.promise;
};

imgToBase64(file).then(function(result){
   $rootScope.result = result;
});

Post request

$http.post(apiURL, {
  name: $scope.name,
  image: $rootScope.result
}).success(function(data) {
      console.log(data);
})

When I click save, only the content of 'name' gets sent and $rootScope.result remains empty. Interestingly, when I log $rootScope.result it does show the result, but it appears empty in the post request. Any idea what could be wrong? Thank you.

Answer №1

Not sure if this aligns with your needs:

$scope.save = function () {
    convertImageToBase64(file).then(function (output) {
        $rootScope.output = output;
        $http.post([...]);
    });
}

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

Transforming the input button into images

I'm new to JavaScript and I'm looking to change the show button and hide button to images instead. The show button image should be different from the hide button image. Can anyone guide me on how to achieve this? Click here for reference $( ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

how to implement a delay in closing a window using JavaScript

I am currently developing a Google Chrome extension and I want to express my gratitude to everyone here for tolerating my sometimes silly questions. The functionality of the extension is quite basic but it works smoothly. However, I am facing an issue wher ...

What is the process for executing a recursive loop?

Recently, I came across this piece of code that fetches data from a third party API located at example.com: $scope.buttonClick = function () { $http.get('https://example.com'). success(function (data, status, headers, config) { ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Ways to determine if the popupState component in Material UI is currently opened

I am currently utilizing PopupState and the Popover component to create a specific element. It is functioning properly, but I have a requirement to modify the icon displayed based on whether the popup is open or closed. Here is the code for my component: ...

Adjusting font size in dynamic containers relatively

Imagine we have a slider named .outer, which adjusts its height based on the width of the viewport. Inside this slider, there is an example slide called .inner that contains some text. However, when we shrink the window width, the content in slide .inner s ...

Each div will display the same image twice when loading the image

I have a grid where images are dynamically loaded with a link to a lightbox. Currently, this is how I am achieving it: $(".selection_thumb").each( function(i) { $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+(++ ...

Is there a way for me to retrieve the name of a newly opened browser tab from the original tab?

I have written a code snippet to create a new tab within the same browser by clicking on a link. function newTab() { var form1 = document.createElement("form"); form1.id = "newTab1" form1.method = "GET"; form1.action = "domainname"; //My ...

Tips for handling a disabled button feature in Python Selenium automation

When trying to click this button: <button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button> I need to remove the disable attribute to make the button clickable. This ...

After running `npm uninstall -g angular-cli`, I thought I had successfully removed angular-cli from my system. To my surprise, when I checked `ng --

What's the deal here? I uninstalled angular-cli globally on my laptop by running npm uninstall -g angular-cli, and now it's gone. But on my desktop, I can still use ng --version even after removing angular-cli globally. Any idea what's ha ...

Retrieve custom content from a database using Laravel and Ajax when clicking on a navigation bar

Recently, I've started working with Laravel 7 and AJAX. One of the features I want to implement is a 'product's name' navbar that displays product details in a div without refreshing the page when clicked. I came across a demo showcasin ...

Using the map function with a React onClick handler

After tirelessly scouring the internet for answers to my query, I've hit a dead end. My goal is to implement a basic react click handler on my button, but for some reason, it just won't cooperate. It's likely something incredibly straightfor ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

A step-by-step guide on selecting a checkbox within an alert popup using Selenium with Java

Hello everyone, I am struggling to find a solution for checking and unchecking a checkbox located in an alert window or modal pop-ups. We have three types of pop-ups: alert, confirm, and prompt. Specifically, in the confirm popup, there is a checkbox t ...

Can you explain the distinction between incorporating and excluding the keyword "await" in the following code snippets?

Currently, I'm diving into an MDN article that covers async/await. I've grasped the rationale behind using the async keyword preceding functions, yet there's a bit of uncertainty regarding the await keyword. Although I've researched "aw ...

When a user clicks on an image, I would like to dynamically resize it using a combination of PHP

Although I have a good understanding of CSS and HTML, my knowledge of Javascript is limited. I am looking to add an interactive element to my website where an image enlarges gradually when clicked and smoothly moves to the center of the screen in one con ...

Could the php function json_encode() be a security risk if used within a script tag?

A while back, I had read OWASP's XSS Prevention Cheat Sheet and created a wrapper function that included JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP by default to ensure safety. However, a user on Freenode/##php pointed out that this approac ...

Tips for establishing a shared child state within an AngularJS application

Is it possible to activate an authenticating modal when the token expires on the client side? I would like for this to be a universal child state that can be accessed from any state. Can this be achieved? ...