Steps for creating an AJAX request in AngularJS with parameters

I'm encountering a syntax error while attempting to fetch the user's location in AngularJS using an AJAX call.

app.controller('locationController', function($scope, $window) {

  $window.navigator.geolocation.getCurrentPosition(function(position) {
    console.log(position);
    var lat = position.coords.latitude;
    var long = position.coords.longitude;

    $scope.$apply(function() {
      $scope.lat = lat;
      $scope.long = long;
    });
  });

  var city = function() {

    http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="
      lat ","
      long "&sensor=true").success(function(response) {
      console.log(response);
    });
  }
});

The specific error I'm facing is related to tokens; it requests deleting a token.

Answer №1

Upon review, there are three key issues that need addressing:

  1. The concatenation of strings in the http.get call seems to be incorrect.
  2. lat and long variables appear to be out of scope within the city function. Perhaps you intended to use $scope.lat and $scope.long?
  3. You have not injected the http service properly for use.

    app.controller('locationController', function($scope, $window, $http) {    
       $window.navigator.geolocation.getCurrentPosition(function(position) {
          console.log(position);
          var lat = position.coords.latitude;
          var long = position.coords.longitude;
    
          $scope.$apply(function() {
             $scope.lat = lat;
             $scope.long = long;
         });
      });
    
      var city = function() {
    
        $http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="
           + $scope.lat + ","
           + $scope.long + "&sensor=true").success(function(response) {
              console.log(response);
        });
      }
    });
    

Answer №2

Give this a try, don't forget to include $http in your code. When using AngularJS for AJAX requests, you have two options - either make a function call with specific action types (GET, POST, UPDATE, DELETE) or utilize a config object like $.ajax.

app.controller('locationController', function($scope, $window, $http) {  // updated
    var city = function() {

    $http.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="  // updated
      lat ","
      long "&sensor=true").success(function(response) {
      console.log(response);
    });
  }
}

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

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Why does the element from a nested array in javascript return as undefined when I try to access it?

Struggling to extract elements from a multidimensional array in JavaScript. Running into an issue where attempting to access elements from arrays within the main array using a variable results in undefined. Surprisingly, I achieve the desired outcome whe ...

Steps for adding an image to Firebase

I recently started a project using React and Firebase. After going through some tutorials, I managed to add and read text from Firebase successfully. Now I am working on displaying data like name, estate, and description in a modal on my React Firebase. M ...

Automatically authenticate ngrok password using Python and JS: A step-by-step guide

I have set up ngrok to expose my localhost running on a Raspberry Pi, and I have secured ngrok with a password. On another computer where I am using Django, which is outside of my network, I want to access a simple server webpage hosted on the Raspberry Pi ...

Showing data in a grid format on a webpage

I created a Java program that generates an array list with values such as Hi, Hello, How, Are, You, Me, They, and Them. In addition, I developed a basic controller to convert these values into JSON format and display them on localhost:8090/greeting like t ...

Press the delete button to remove both the box and text dynamically with JavaScript

My task involves managing a shopping list with delete buttons next to each item. I am trying to use JavaScript to remove both the button and the corresponding text when the button is clicked. So far, my attempts have been unsuccessful. I used document.getE ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Only Chrome causing my JavaScript execution to freeze due to Ajax

When using Ajax, it is supposed to be asynchronous, but for some reason, it seems like it's either stopping or pausing my JavaScript execution and only resuming once the response is received. Here is an example of HTML value: <input value="foo" d ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

What could be causing angularjs to malfunction in this specific scenario?

Recently, I followed a tutorial and implemented the code provided. Inside the angular folder in my libs directory, I have the minified version of Angular JS obtained from https://angularjs.org/. However, the output I am seeing is: {{author.name}} {{autho ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Having issues with Angular http.post not sending data when using subscribe

I'm currently facing an issue with sending data to my API using post.subscribe. Despite the fact that no errors are being thrown, the data is not being sent successfully. It's important to note that the API itself is functioning perfectly. Belo ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

How can I bring in a dynamic MaterialUI theme object from another file?

Could anyone provide guidance on the correct syntax for importing a dynamic theme object from a separate file? I am attempting to retrieve the system theme based on a media query and then dynamically set the theme. Everything works as expected when all t ...

Trouble transmitting AJAX data to Django view

I have integrated a simple checkout feature where users can choose a shipping address from a list of addresses using the 'address' class. Although it functions properly on the server side, I want to implement AJAX to prevent the page from refresh ...

I'm having trouble getting my state to update in React when using useState

I am facing an issue with rendering a component that has a route using react router. The first component contains a button, and upon clicking it should render another component with state passed down from the initial component. However, even though the pag ...

The browser automatically adds a backslash escape character to a JavaScript object

When attempting to send an MQTT message to a topic from my angular app, the message needs to be in a specific syntax: { "Message": "hello" //the space after : is mandatory } However, upon sending the message in the correct format, the browser aut ...

in node.js, virtual machine scripts can import modules using the require function

I am currently developing a command-line interface using node.js that runs an external script > myapp build "path/to/script.js" myapp is a node.js application that executes the script provided as a command-line argument. In simple terms, it performs ...

Tips on stopping the page from scrolling following an ajax request (return false not effective or potentially misplaced)

I am working on a project that involves displaying a tree with information from the Catalogue of Life, including details such as Kingdom, phylum, order, and more. My approach includes using ajax/php to interact with a mySQL database and javascript to handl ...