Error message in JavaScript saying "The response string is undefined

I am working on a program built in angularjs. Currently, I receive JSON data from the server when online, but I am now developing an offline mode for the application.

Despite trying to tackle the issue, I am unable to identify why I cannot resolve it.

In the scenario where the program transitions to offline mode, I save the JSON information to localStorage to retrieve this JSON string.

Within service.js - webServiceCallPost function

webServiceCallPost: function(data, action) {
            console.log("data    "+JSON.stringify(data));
            console.log("action    "+JSON.stringify(action));
            var deferred = $q.defer();
            if (navigator.connection.type != "none") {
                return $.ajax({
                    type: "POST",
                    url: appConst.serviceUrl.service + action,
                    crossDomain: true,
                    dataType: "json",
                    data: data,
                    timeout: 2000000,
                    async: true,
                    success: function(response) {
                        localStorage.setItem(data + action, JSON.stringify(response));

                        deferred.resolve();
                    },


      error: function(xhr, ajaxOptions, thrownError) {
                    $ionicLoading.hide();
                    if (xhr.status == 0) {
                        window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
                    } else if (xhr.status == 404) {
                        window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
                    } else {
                        window.plugins.toast.showShortBottom($translate.instant("timedOutError"));
                    }
                },
                beforeSend: function() {},
                complete: function() {}
            });

        } else {
            window.plugins.toast.showShortBottom($translate.instant("checkNetWorkConnection"));
            $ionicLoading.hide();
            var response1 = JSON.parse(JSON.stringify(localStorage.getItem(data + action)));
            return $http.get('').then(function(response) {
                return response1;
            });
        }
    }

And within controller.js - Retrieving response.

Services.webServiceCallPost('', appConst.services.get_menu_card).then(function(response) {
                    $ionicLoading.hide();
                    console.log("Response:     " + JSON.stringify(response));

                    if (response[1].response.status == 1) {
                        if (response[0].data.menu.length > 0) {
                            var categoryResponse = [];
                            angular.forEach(response[0].data.menu, function(value, key) {
                                if (value.menu_image_name != '') {
                                               var extraData = {
                                                        imageUrl: appConst.serviceUrl.menu_image_url + value.menu_image_name
                                                    }
                                } 
                                else {
                                    var extraData = {
                                        imageUrl: 'img/screen.png'
                                    };
                                }
                                angular.extend(value, extraData);
                                categoryResponse.push(value);
                            });
                            $rootScope.categories = globalMethods.getDashboardGridView(categoryResponse, 2);
                        }
                        if (response[0].data.addons.length > 0) {
                            $rootScope.totalAddons = [];
                            angular.forEach(response[0].data.addons, function(value, key) {
                                var extraData = {
                                    "finalCost": value.price,
                                    "quantity": 1,
                                    imageUrl: appConst.serviceUrl.addon_image_url + value.addon_image
                                };
                                angular.extend(value, extraData);
                                $rootScope.totalAddons.push(value);


 });
                    }
                    $scope.getSiteSettings();
                }
                $rootScope.dashboardHistoryId = $ionicHistory.currentHistoryId();
            });

Console Output : When inspecting the JSON output, it appears consistent.

Online Response :

Cached Response :

Issue: TypeError: Cannot read property 'status' of undefined

Upon attempting to retrieve the response, the status property is accessed without any problem when online 1.response.status. However, in offline mode with cached response 1.response.status, the status is returning as undefined even though the data is exactly the same. Why is this happening?

https://i.sstatic.net/yDFYZ.png

Answer №1

When this snippet of code is executed

let cachedResponse = JSON.parse(JSON.stringify(localStorage.getItem('' + appConst.services.get_menu_card)));

and if it involves an asynchronous request

console.log("Cached Response:     " + cachedResponse);

the execution won't wait for the asynchronous call to complete, potentially leading to a printout of undefined values.

Answer №2

Appreciate the response to @PatrickEvans

Perhaps you haven't returned the correct value... Also, avoid using JSON.parse(JSON.stringify(localStorage.getItem()). Just use JSON.parse(localStorage.getItem()) since localStorage items are already strings. Stringifying it can cause issues with your intended outcome.

Additionally,

Resolve $q.when(response1);

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

AngularJS displays the value from the dropdown menu in the input field

I am looking for a way to display the text "login" and "password" from $scope.logins when a user clicks on them in a dropdown menu. $scope.logins = [{ "login" : "log", "password" : "pass" }] Here is the HTML code: <div class="drop ...

New update to Angular Currency Filter - Now including Symbol Â!

While utilizing angular's currency filter, I noticed an unexpected extra symbol being outputted: Â. This is the HTML code: {{totals.subtotal | currency}} {{totals.tax | currency}} {{totals.total | currency}} The 'totals' object looks lik ...

Tips for refreshing a live ajax call to animate a circle

Currently, I am utilizing the gaugeMeter plugin to dynamically display the CPU usage of my elasticSearch Host. While the values are being displayed correctly, there seems to be an issue with the animation of the gauge/circle itself. Instead of the indicato ...

ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated! function onlyOne(checkbox) { var checkboxes = document.getElement ...

Discovering the active controllers in current AngularJS implementation

Is there a method to obtain a current list of active controllers? I have an object within my factory and a controller named "myController". Thus, I want to set myFactory.object={} (empty this object) if the myController is no longer connected to the modu ...

Angular directive becomes disabled when transferred between different DOM elements

In my app, I utilize a modal service that handles the opening and closing of modals. The modal retrieves its content from a specific div with an ID located within a hidden container element. This process typically functions correctly. The issue I am encou ...

Tips for concealing one modal and revealing a different one upon page refresh

I am facing an issue with my modal form. What I want is for the modal to close upon submitting the form, then for the page to reload, and finally for the success modal to be displayed. However, when I clicked submit, the success modal ended up appearing o ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

Determine the active animation on an element using jQuery or JavaScript

Can you provide the code for the know_anim() function that can determine which animation is currently running on the '#div' element? Check out the jsFiddle link for reference:https://jsfiddle.net/himavicii/bL0nsjeL/ function moveLeft() ...

Meteor: Transforming MongoDB server logic for the client's use

Although I can successfully retrieve data from the meteor mongo terminal using this code, I am struggling to fetch data from the client side. I realize that the syntax for the client side is different, but being new to this environment, I am unsure of ho ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

how to bind data to an array in Angular

I recently developed an Angular 7 application that features the capability to dynamically add and remove controls. However, I am facing challenges when it comes to binding the data to the form. In the code snippet below, I am focusing on the process of ad ...

Utilizing lodash and JavaScript for data normalization techniques

Converting data from two dimensions to one dimension using lodash rel href link1 url1 link2 url2 link3 url3 url4 link4 url4 url5 Expected output after normalization rel href link1 url1 link2 url2 link3 url3 link ...

Ways to exclusively trigger the onclick function of the primary button when dealing with nested buttons in React.js

Let me elaborate on this issue. I have a List component from material-UI, with ListItem set to button=true which makes the entire item act as a button. Within the ListItem, I have added a FontAwesomeIcon. To hide the button, I set its style to visibility: ...

Retrieve and manipulate custom headers from a webview within an AngularJS app

I have implemented an angular application within a webview using the following code: WebView.loadUrl(String url, Map<String, String> additionalHttpHeaders) In order to manage the content and display it appropriately, I am maintaining a state in my ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Transfer a GET parameter from the URL to a .js file, then pass it from the .js file to a

Hey there, I'm currently using a JavaScript file to populate my HTML page with dynamic data. The JS file makes a call to a PHP file, which then fetches information from my SQL database and echoes it as json_encode to populate the HTML page. The issue ...

Automatically include the date as a column heading along with name and ID

I recently came across a guide on how to dynamically add dates as column headers in a table. However, I encountered an issue where I couldn't add new columns for 'Name', 'Age', and 'Section' before the dynamically generat ...

css failing to load properly following javascript redirection

Upon clicking the button labeled id=cancel, the user will be directed to index.php. $('#cancel').click(function() { if(changes > 0){ $('#dialog-confirm').dialog('open'); }else{ window.location.href = ". ...