The toaster fails to pop up once the AJAX method successfully completes

I am new to angularjs and web development in general. I have an ajax request that sends information to the server after a button click. When the request returns success, I want to display a toast notification confirming that the request was sent successfully. However, the toast does not appear, even though there is a console log showing that the request was sent. Why isn't the toast popping up?

Note: The toast does work when placed outside the success function of the ajax call.

Thank you in advance.

Here is my code:

(function() {
    'use strict';

    angular
        .module('app.dashboard')
        .controller('NotificationController', NotificationController);

    NotificationController.$inject = ['$resource', '$http', '$state','toaster'];
    function NotificationController($resource, $http, $state, toaster) {
        var vm = this;

        activate();


        vm.alertSubmit  = function() {
            console.log(vm.subject);
            console.log(vm.htmlContent);

            const item = {

                'subject':vm.subject,
                'body': vm.htmlContent
            };

            //toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text); If I try this line the toast does appear.

            //console.log(item);
            //console.log(JSON.stringify(item));
            $.ajax({
                type: 'POST',
                accepts: 'application/json',
                url: 'api/pushnotification',
                contentType: 'application/json',
                data: JSON.stringify(item),
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                    toaster.pop(vm.toaster.type, "Failure", "Message wasn't send.");
                },
                success: function (result) {
                    console.log(result);
                    toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
                }
            });
            return false;
        };

        function activate() {
          // the following allow to request array $resource instead of object (default)

            $http
                .get('api/auth')
                .then(function(response) {
                    // assumes if ok, response is an object with some data, if not, a string with error
                    // customize according to your api                
                    if (!response.data) {
                        $state.go('page.login');
                    }
                    else
                    {
                        var actions = {'get': {method: 'GET', isArray: true}};
                        vm.toaster = {
                            type: 'success',
                            title: 'Success',
                            text: 'Message was sent successfully.'
                        };

                        //vm.pop = function () {
                        //    toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
                        //};

                    }
                }, function() {
                    $state.go('page.login');
                });         
                console.log("activate func"); 
        }
    }
})();

Answer №1

It has been recommended by @georgeawg to utilize the $http service:

$http.post('/someUrl', data, config).then(successCallback, errorCallback);

You can update your code as follows:

$http.post({
      'api/pushnotification', // Post URL
       JSON.stringify(item),  // Data to be sent
       contentType: 'application/json' // Header Config
}).then(
        // successCallback
        function (result) {
            console.log(result);
            toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
        },

        // errorCallback
        function (errorThrown) {
            alert(errorThrown);
            toaster.pop(vm.toaster.type, "Failure", "Message wasn't send.");
        },
);

This is an alternative to your existing code:

$.ajax({
            type: 'POST',
            accepts: 'application/json',
            url: 'api/pushnotification',
            contentType: 'application/json',
            data: JSON.stringify(item),
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
                toaster.pop(vm.toaster.type, "Failure", "Message wasn't send.");
            },
            success: function (result) {
                console.log(result);
                toaster.pop(vm.toaster.type, vm.toaster.title, vm.toaster.text);
            }
        });

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

Is there a way to automatically activate a navbar item without the user having to click on a navigation link first?

I'm currently working on a website and I've configured the navigation items so that when you click on a nav-link, it changes the active class to the clicked link. However, I'm wondering how I can set a specific link to be active by default ...

Retrieving information from various object keys using Vue.js

Currently, I am in the process of setting up a feature in my application where users can select an option from a list and the background of the app will change based on their selection. Imagine having a list structured like this: <li v-for="item in it ...

Ways to Share Multiple Table Checkboxes

As someone new to development, I encountered the following issue. https://i.sstatic.net/D8EIb.png In the image above, you can see that I have a pagename and three Radio buttons - view, edit, and update. Here is my code: <td>{{product name}} < ...

Developing bi-directional binding for newly generated elements post initial compilation

I have developed a directive that dynamically generates a form based on a JSON received from the server. I am trying to include the ng-model attribute in the input elements so that I can access the input values once the user enters them and clicks submit. ...

Exploring the Differences Between Backbone.js' ID, idAttribute, and CID

After spending a few weeks learning Backbone.js, I've become proficient in using views with models, routers, and collections. However, there are still some significant gaps in my understanding: Can you explain the relationship between id, cid, an ...

Building dynamic web applications with PHP Slim and AngularJS, utilizing JSON data

I've been attempting to transmit data from my AngularJS Project to a PHP Server with PHP Slim, but despite trying everything I know, nothing seems to be working. PHP SLIM SERVER $app->get('/create',function() use ($app) { $data ...

Looking for a fully customizable event and booking calendar?

Currently, I am searching for a unique event and booking calendar that provides the ability to customize each cell or day with our desired content. While most calendars only allow for inputting events as text, we require a solution that enables us to add ...

How can I use try-catch in JavaScript to call the same function again in the catch block

When encountering a scenario in JavaScript where a Try Catch block fails due to some issue, what is the best approach to handle this and retry the same operation until it is successful? For example: const getMyDetails = async()=>{ try{ await ge ...

What is the purpose of using @ViewChild to access a component's function from another component?

During a discussion with my tutor, I learned that in Angular we can utilize functions defined in any service by simply importing the service. However, unlike services, components cannot be directly imported into other components. To access a function from ...

How to retrieve an array value within a function in AngularJS

<select class="form-control" id="column" ng-model="selectedcolumn" ng-options="column for column in columns"></select> <input type="text" ng-model="test[selectedcolumn]" ng-change="search()" /> Is there a way to retrieve the value o ...

Guide to filtering an array within ag-grid when defining a column

After switching from using DataTable to ag-grid, I encountered a challenge. In DataTable, I accessed the first element from the attributes array where typeName='ItemType'. Now, I am looking to achieve the same functionality in ag-grid. Any sugges ...

What is the alternative to $templateCache in Angular2 and how can CachedResourceLoader be utilized in its place?

While I have come across 2 similar questions on Stack Overflow and here, none of them seem to provide a solution. After delving into the Angular repository, I stumbled upon this issue where they inquire about an alternative for templateCache in Angular 2, ...

Error: JSON parsing error due to unexpected token C at the beginning of the string

When using ajax and json formatting, I am encountering this message. In PHP, the code array("message" => "Success", "data" => $data) is displayed successfully. However, it is not able to callback to ajax. How can I resolve this issue without deleting ...

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

Obtain data from a local JSON file using the http.get() method in Angular 2

I am attempting to utilize the http.get() method in Angular 2 to load a local JSON file. I followed a suggestion from Stack Overflow that involves modifying my app.module.ts: In this example, I have imported the HttpModule and the JsonModule from @angular ...

Are the elements in the second array the result of squaring each element in the first array? (CODEWARS)

I am currently working on a 6kyu challenge on codewars and I've encountered a frustrating issue that I can't seem to figure out. The task at hand involves comparing two arrays, a and b, to determine if they have the same elements with the same mu ...

Combine two arrays in PHP similar to how arrays are pushed together in JavaScript using the `array_merge()` function

I am trying to combine two arrays in PHP: Array1 = [123,456,789]; Array2 = [1,2,3]; The desired combination should look like this: Array3 = [[123,1],[456,2],[789,3]]; In Javascript, I can achieve this using the push() function within a for loop: Arra ...

What is causing my Cordova hook to require two executions before functioning properly?

Currently, I am working on a Cordova project that involves the use of browserify to utilize require() in the mobile app. The setup works well, so now my goal is to automate the browserifying process of my js files by integrating it into a Cordova hook. Thi ...

Using JQuery to target the input value based on its ID

When trying to extract the value of the input with id "registration_type," I entered the following command in the console: $('#registration_type') The output displayed was: <input id=​"registration_type" name=​"contact_registration[ty ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...