Ways to retrieve a variable from outside of a function

I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am unable to access response.data.data[0]._id outside the function as it is a local variable. Is there any way to bind the course_id with batchData object?


app.controller('batch_add', function($scope, $http) {
    $http.get("/courses/getall")
    .then(function(response) {
            if (response.data.length == 0) {
                $scope.items = [{ course_name: "No data", course_desc: "No data", course_fees: "No data" }];
            } else {
                $scope.items = response.data.data;
                var course_name_items = []
                for (var i = 0; i < $scope.items.length; i++) {
                  course_name_items.push($scope.items[i].course_name)
                }
                $scope.course_items = course_name_items;
            }
        });

    $scope.batch_status_items = ['Pending', 'Running', 'Finished', 'Canceled' ]

    $scope.batchData={};
    $scope.login =  {"batchData" : $scope.batchData};
    $scope.submitForm = function() {
    $scope.login =  {"batchData" : $scope.batchData};
    $scope.fail = false;
        $http({
            method  : 'POST',
            url: 'batches/add',
            data    : $scope.login
    })
        .success(function(data) {
            if (data.success == true) {
                $scope.fail = true;
                $scope.success = true;
                $scope.success_message = data.message;
                var courseName = $scope.batchData.course_name;
                $http.get("/courses/search/"+courseName)
                .then(function(response) {
                        if (response.data.length == 0) {
                          console.log("error");
                        } else {
                            $scope.batchData.course_id= response.data.data[0]._id

                        }
                    });
                        toastr.options = {"positionClass": "toast-bottom-right"}
                        Command: toastr["success"]("A new batch has been added!")
                } else {
                    $scope.fail = true;
                    $scope.success = false;
                    $scope.error_message = data.message;
                    console.log($scope.success_message);
                   //  toastr.error('Something went wrong.', 'Ooops!')
                }                      
          });
$scope.batchData.course_id = response.data.data[0]._id
        };
    });

Answer №1

Have you considered retrieving the course ID before sending it to the database with batchData?

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

Building connections in parse.com using various classes (JavaScript SDK)

Currently using parse.com in conjunction with the JavaScript SDK. Despite my extensive research, I have been unable to find any examples that directly address the issue I am facing. Here is the specific goal I am striving to accomplish: I aim to establi ...

I can't believe this ReactJs project generated this code automatically

What does this automatically generated code do in my ReactJs app and what are the advantages of including it? <div class="nsc-panel nsc-panel-compact nsc-hide"> <div class="nsc-panel-move"></div> <div class=" ...

Sending postMessage during the beforeunload event does not work as expected

When postMessage() is triggered within the beforeunload window event in an Ionic 2 browser, I've noticed that the message doesn't make it to the parent. However, if the same message is sent during the unload or load event, it is received successf ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

Customize input box type based on JSON data using ng-repeat directive in AngularJS

Looking to implement a dynamic form using angular JS. I can successfully use ng-repeat to iterate through JSON fields and display an input box for each. Now I need to customize the input type based on field data from JSON, whether it's 'input&a ...

Background PHP/JS authentication through HTTP

Recently, I developed a PHP website that includes embedded web-cam snapshots which refresh every 2 seconds using JavaScript. For the first camera, I can easily log in using URL parameters like this: cam1-url?usr=usr&pwd=pwd. However, the second camer ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows: def scoreValue = new HashMap<String,String>(); scoreValue.put("0","poor"); scoreValue.put("1","good"); ... retu ...

Oops! An issue occurred on the server: ReferenceError - 'window' is not defined. This error occurred during

I'm looking to integrate a Microsoft Login Button into a Next Js application using Material UI. However, after adding the necessary package from NPM and refreshing the page, I encountered the error mentioned above. When I tried setting ClientId="a973 ...

Slider Jquery - Displaying Half-Step Visual Bar Lengths

JSFIDDLE $(function() { $( "#slider-range-min" ).slider({ range: "min", value: 5, min: 0, step: .5, max: 10, slide: function( event, ui ) { $( "#amount" ).val(ui.value); ...

Can the value of ng-model be altered without using ng-change function?

Can the ng-model value be altered without using the ng-change function? The method below does not seem to work. <div ng-app="myApp"> <div ng-controller="MyCtrl"> <input id="checkbox" type="checkbox" ng-model="field"> <div> {{field ...

Why is the last move of the previous player not displayed in this game of tic tac toe?

Why does the last move of the previous player not show up in this tic-tac-toe game? When it's the final turn, the square remains empty with neither an "O" nor an "X". What could be causing this issue? Here is the code snippet: The HTML code: <div ...

Steps for Implementing an Event Listener in JavaScript

While working on a page in Chrome, I encountered an issue where I wanted a modal to show up when a user clicked on an image. However, the functionality was not working as expected on my localhost. Upon further inspection, I believe there might be a problem ...

Using Javascript to group elements by JSON data

I have an array of JSON objects and I'm attempting to organize it by a specific element. I came across some code example on grouping JSON format from this link const groupBy = prop => data => { return data.reduce((dict, item) => { ...

What is the process for connecting two scripts together?

Purpose : I am currently working on a Firefox add-on with the goal of tracking the online status of my team members in a game. Current Progress : I have developed an initial JavaScript script that runs upon opening the browser. This script creates and ...

Strategies for capturing POST data sent to a JavaScript webpage

The request is sent from an external source beyond my control xyz.php <form action='https_:_//xyz.com/javascriptFile' method='POST'> <input type='text' name='data' /> </form> to: (My custom f ...

JavaScript takes the spotlight before CSS

Currently experiencing this issue in Chrome, although Firefox seems to be working fine so far. Here is a greatly simplified version of the problem: HTML: <div class="thumbnail"> <a href='#' id="clickMe">Click me!</a> </d ...

What are some techniques for managing scrolling within a particular element?

I am currently working with Vue.js and utilizing Element UI components. I want to incorporate a scroll management function to achieve infinite scrolling. To better understand, please refer to the screenshot in the Example section: Despite trying differen ...

Steps to modify the servletRequest's content length within a filter

My main objective is to secure the POST body requests sent from my web application to my service by encrypting them. This encryption process takes place within a filter in my system. However, I've encountered an issue related to content length. When ...

Are Primereact and MUI JOY Styling at Odds?

here is the image of datatables and button I am currently using Primereact and MUI Joy in the same project, but I am facing an issue where the Primereact styling does not load properly. I'm not sure if it's due to a conflict with MUI Joy or some ...