The variable $http request is not defined in this context

When I perform a GET request on my backend to fetch JSON data, I am encountering an issue with storing a portion of the data in a variable for later use. Despite following similar steps in another controller where it worked fine, the variable always ends up being undefined. Can someone please help me identify what I might be doing wrong?

Below is the snippet of code in question:

 var itemNumber;
 $http.get(URLtoServer + 'serialNumber/' + $stateParams.serialNumber + '/?format=json').success(function(dataSerialNumber){
      itemNumber = dataSerialNumber.id;
    }).error(function(){
      //code
    });

    console.log(itemNumber);
    item.number = itemNumber; 

After editing the POST call:

var postPromise = $http.post(URLtoServer + 'problem/', item);

  postPromise.success(function (response) {
    angular.extend(item, response);
    showIssueReportedAlert($mdDialog); 

    $http.get('assets/settings/general.json').success(function(data){
      companyURL = data[0].url;

      $timeout(function(){
        //$window.location.href = companyURL;
      }, 3000);
    });         
  });

  postPromise.error(function(){
    showErrorAlert($mdDialog);

    $scope.renderSendbutton = true;
    $scope.showProgressCircular = false;
  });

Answer №1

One way to handle your POST request is to encapsulate it within a function, which can then be called within the success callback of your GET request.

 var itemNumber;
 $http.get(URLtoServer + 'serialNumber/' + $stateParams.serialNumber + '/?format=json').success(function(dataSerialNumber){
      itemNumber = dataSerialNumber.id;

       console.log(itemNumber);
       item.number = itemNumber; 
       doPostCallNow(); //Initiating the POST request
    }).error(function(){
      //handle error
    });

function doPostCallNow(){
    var postPromise = $http.post(URLtoServer + 'problem/', item); 
    //Any additional code can be written here
}

Answer №2

If you are performing an asynchronous get request, it means that the response is not immediate. In this scenario, you are trying to assign the itemNumber (which is currently undefined because the get request has not completed yet) to your item.number.

To ensure that the assignment is done correctly, you should perform it within the callback function:

 var itemNumber;
 $http.get(URLtoServer + 'serialNumber/' + $stateParams.serialNumber + '/?format=json').success(function(dataSerialNumber){
      itemNumber = dataSerialNumber.id;

       console.log(itemNumber);
       item.number = itemNumber; 
    }).error(function(){
      //code
    });

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

Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button. ...

What is the best method for using XMLhttpRequest in PHP to append options to a select element?

I'm looking to dynamically fetch values from a MySQL database using PHP and then add them as choices within a select element. Here is my HTML code: <label for='listDivision'>Division</label><select id='listDivision&apos ...

What is the process for transferring selections between two select elements in aurelia?

I am attempting to transfer certain choices from select1 to select2 when a button is clicked. Below is my HTML code: <p> <select id="select1" size="10" style="width: 25%" multiple> <option value="purple">Purple</option> &l ...

Display a list of records retrieved from a Firebase query using ngFor to iterate through each instance

I'm currently using firebase and angular to work on a billing list project. The list contains data showing information for a specific month, you can refer to the imagehttps://i.stack.imgur.com/ZR4BE.png While querying the list was smooth, I encounte ...

leveraging embedded jetty for developing a web-based interface

As a newcomer to web development and using embedded Jetty, I have created the source code below in Eclipse IDE. I need to programmatically start the Jetty server and cannot use the command line to do so. The web interface must be lightweight due to the li ...

`I am experiencing issues with the HTTP Post functionality`

Whenever I click on the button displayed in the index.html code, an error occurs when the "$http.post" call is made. The web page then displays an alert saying 'Error!', preventing me from saving the new JSON file due to this issue. I need help ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

Tips for serializing form inputs within a .change event using javascript, PHP, and CURL

I have a small project underway that involves using Ajax to retrieve data from a database and update a page. The user is able to build a dynamic query, creating a chain of query strings where each item in the chain affects the next one. This results in a l ...

Protractor issue: Out of bounds error encountered when attempting to use a function for the second time

I encountered an issue with a function that selects a category from a list of available categories. The function worked perfectly in my initial test, but when I used it with a different valid category name for another test, it failed and displayed the foll ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

Vue's innate lifecycle hook

I am looking for a way to automatically run a specific function as a beforeMount hook in every component of my Vue project without having to declare it individually. Essentially, I want a default behavior where if the hook is not explicitly stated in a com ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

Ensure that PHP errors are reported in JSON format, following the standard content-type guidelines

When working with AngularJs for a single page application that communicates with serverside PHP via JSON, I encountered an issue regarding error reporting from PHP. The PHP header sets JSON, but the error reporting settings are: php_flag display_errors 1 ...

Angular-Translate fails to function within a tag's attribute

For my project, I utilize angular-translate. One of the key definitions looks like this: { "paging":{ "first":"First", "last":"Last", "next":"Next2", "pre":"Previous" } } I implement it in the following way: <uib-pagination first-tex ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

From jQuery to ReactJS: Migrating to a Modern

As I venture into converting existing jQuery code to React.js, I must admit that I am quite new to React and still in the learning phase. So please bear with me if my questions sound a bit silly. Here is the structure I am working with: <ul> &l ...