The function is not functioning properly due to an issue with the HTTP request

I am working with an AngularJS Framework controller.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {


 var locations =[]; var map; var markers = [];

$scope.mappa = function(){
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 37.507033, lng: 15.080257}, 
        zoom: 8
      });
}

$scope.insert = function(){

         $http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
    .success(function(data) 
            {locations = data;});

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
        marker = new google.maps.Marker({
             position: new google.maps.LatLng(locations[i][0], locations[i][1]),
             map: map
        });
        markers.push(marker);
    }

    for (i = 0; i<markers.length; i++){
     markers[i].setVisible(true);
   }
};

I have a button in my HTML file that triggers the insert function. However, I noticed that the button only works the second time it is clicked. Interestingly, if I move the HTTP request outside of the function, the button works immediately. Why is that?

$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data) 
        {locations = data;});

$scope.insert = function(){

var marker, i;

for (i = 0; i < locations.length; i++) {  
    marker = new google.maps.Marker({
         position: new google.maps.LatLng(locations[i][0], locations[i][1]),
         map: map
    });
    markers.push(marker);
}

for (i = 0; i<markers.length; i++){
 markers[i].setVisible(true); }
};

Answer №1

Utilize an asynchronous method to handle the code insertion within the callback for success.

$http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati")
.success(function(data) {
    var marker, i;

    for (i = 0; i < data.length; i++) {  

        marker = new google.maps.Marker({
             position: new google.maps.LatLng(data[i][0], data[i][1]),
             map: map
        });

        markers.push(marker);
    }

    for (i = 0; i<markers.length; i++){
        markers[i].setVisible(true); }
    }
});

Answer №2

When running this code, the button only functions properly on the second attempt.

Although it may seem like it works the first time, the AJAX request is asynchronous, causing the location variable to not be populated when you try to use it. On the subsequent click, the data has already loaded and location is set and cached.

To address this issue, make sure to perform your actions within a callback function:

$scope.insert = function () {

    $http.get("http://localhost:8080/SistemiDistribuiti/rest/Point/Trovati").success(function (data) {
        var marker, i, locations = data;

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][0], locations[i][1]),
                map: map
            });
            markers.push(marker);
        }

        for (i = 0; i < markers.length; i++) {
            markers[i].setVisible(true);
        }       
    });

};

Additionally, once you have resolved the issue, consider refactoring your code by moving the request logic into a reusable service. It is not recommended to handle requests directly in the controller:

$scope.insert = function () {
    locations.get().then(function(data) {
        var marker, i, locations = data;
        // ...
    });
};

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

Stop the entire page from scrolling when scrolling within a specific div element

I am looking for a solution to prevent the page from scrolling back to the previous section while scrolling within a specific div element. Currently, I am using Alvarotrigo's fullpage scroll plugin, although I am not sure if that is relevant to the is ...

Information is only displayed within the Node Request function and is not accessible to

I am currently developing a small web scraping tool using Node (Express) to search URLs from a list. However, I'm encountering an issue with accessing the results of the search outside of the request callback function in a forEach loop. Can anyone hel ...

the cached token retrieved by adal is consistently empty

To retrieve a cached token, I am utilizing the react-adal api import { authContext, } from '../auth' const AvatarContainer = () => { getPersonPhoto(authContext) return ( <Avatar /> ) } async function getPersonPhoto(au ...

Can a valid HTML structure be reconstructed from a fragment?

Imagine you have just <td>text<td></tr>. Clearly, by itself, it is not considered valid HTML (and neither is just <td>...</td>). Is there a simple method to reconstruct a valid HTML structure from this fragment? It should lo ...

Extract PHP variable and incorporate it into JavaScript code

After doing some research online, I was unable to find a solution to my issue. Can anyone provide assistance with this problem? I currently have a javascript variable that contains the name of a PHP session address. I am trying to access this session valu ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

I am looking to utilize the JavaScript YouTube API to seamlessly upload a video from my website directly to YouTube

Currently facing an issue with uploading a video from my webpage to YouTube using the JavaScript YouTube API. The error code I'm receiving is "User authentication required" (401). Can anyone provide me with a demonstration example in JavaScript that s ...

Converting an object to a string using AngularJS within a directive

Can anyone assist me in ensuring that AngularJS preserves non-string values in directive attributes? While searching for a method to display a tree structure in HTML from JSON data, I came across this code snippet: http://jsfiddle.net/n8dPm/ I've be ...

Refresh a Particular Section of a Website Without Having to Reload the Entire Page

I have this PHP script that I'm using to read specific phrases from a text file and then display one of them randomly on a webpage. Currently, the only way to see a new random phrase is by refreshing the entire page. I'm wondering if there is a w ...

Accessing JSON data in AngularJS from Node.js as the backend and SQL database

I am currently working on a project that involves setting up a node.js server in the backend and using AngularJS in the frontend. In order to fetch information from an SQL database, I have implemented a simple GET request as shown below: req.execute(&apos ...

Using JQuery to Enhance the Highlight Effect: Tips and Tricks

Exploring the functionality of the "highlight" JQuery effect: http://docs.jquery.com/UI/Effects/Highlight You have the ability to modify the background color of any DIV element with a fade in/out effect. However, the provided example demonstrates trigge ...

Switch out two for loops with the find or filter method in JavaScript

In my unique approach, I am showcasing a variety of product details lists based on availability in various shops. To achieve this, I have implemented the following method. for (let i = 0; i < this.prodList.length; i++) { let setContent = false; for ...

The JavaScript code is not being executed, as the address bar displays the function name instead

In my project, I have created numerous "js-classes" with various functions spread across different files. Unfortunately, the codebase is too large to share entirely. However, towards the end of the project, I encountered a bug where a specific function wa ...

Having trouble loading CSS and JavaScript files in CodeIgniter?

In my project, I am utilizing Bootstrap as a template. However, when attempting to access Bootstrap in Codeigniter, the page fails to load the CSS and JavaScript files. I have included the URL in autoload.php $autoload['helper'] = array('url ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

What causes AngularJS to alter my GET parameters when using $http?

I am currently making a basic GET request to a REST service in order to obtain a list of users and sort them by their usernames. Using jQuery, the process runs smoothly: $.getJSON('/api/users', { sort: { username: 'asc' } }, funct ...

Tips for managing content and tables that exceed their container's boundaries

On my webpage, I have a slide-out sidebar that shifts the other contents and causes overflow with a scrollbar. I want the content to remain inside the window and adjust according to the available space. Image of Slide-out Sidebar As seen in the image, t ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

In the middleware, the request body is empty, but in the controller, it contains content

Below is my server.js file: import express from "express"; import mongoose from "mongoose"; import productRouter from "./routers/productRouter.js"; import dotenv from "dotenv"; dotenv.config(); const app = expres ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...