Making HTTP requests in AngularJS

My current project involves a specific functionality: Using AngularJS, I want to trigger an ajax call to retrieve JSON data from the server when a button is clicked.

Without the button interaction, the code below works perfectly:

<!DOCTYPE html>
<html>

<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

<div ng-app="" ng-controller="customersController"> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
function customersController($scope,$http) {
 $http.get("http://www.w3schools.com//website/Customers_JSON.php")
  .success(function(response) {$scope.names = response;});
}
</script>

</body>
</html>

However, as soon as I implement the button click feature, the data fails to display upon clicking the button.

<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>

<div ng-app="" ng-controller="customersController">
    <button ng-click="getData()">Get Data</button> 

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
    function customersController($scope, $http) {
     $scope.getData()=   $http.get("http://www.w3schools.com//website/Customers_JSON.php")
         .success(function (response) { $scope.names = response; });
    }
</script>

</body>
</html>

I would greatly appreciate any assistance with this issue!

Answer №1

You have a couple of small mistakes in your code.

Firstly, you cannot assign a value to the return of a function. Take a closer look at this line: $scope.getData()= $http....... This instructs JavaScript to execute the $scope.getData function, but you cannot use an equal sign immediately afterwards to assign a value to that return. It is likely that $scope.getData is undefined, leading to a script error.

Secondly, even if you fix the first issue by changing it to $scope.getData = $http...., you are still calling the $http.get immediately and then assigning the return to $scope.getData. What you actually want to do is create a reusable function like this:

$scope.getData = function () {
    // function body
}

By addressing these two issues, your code should work perfectly.

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

Issue with Laravel: Using `$request->all()` results in an empty array when called using JSON XHR

Having trouble using $.ajax and only the XMLHttpRequest for sending JSON to a Laravel controller. Keep getting 500 errors when attempting to make the request. Here's the method I'm using to send the data: const sendEdit = function(){ ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

Encountering a problem while attempting to update react-router from version 5 to version 6

I am encountering a typescript error after upgrading React-router-dom from v5 to v6. How can I resolve this issue? Below is the code snippet. Thank you in advance. export function withRouter(ui: React.ReactElement) { const history = useNavigate(); con ...

Javascript - Iterating through nested arrays and objects to apply filtering

I am currently trying to fetch specific arrays based on a certain criterion. I am a bit unsure about how to go about filtering the arrays, so I thought I would seek clarification here. Essentially, I have a list of courses and I want to extract all the c ...

Learn how to use Angular for submitting a form with AJAX interactions

Hello, I am a beginner with Angular and I have been trying to submit a form and check in my MySQL database if the user is present. All of my code works because when I directly input the JSON into my PHP/CodeIgniter code, I get the employee that I'm lo ...

Leverage the data retrieved from an Ajax request to generate dynamic content

I'm currently working on a project that involves creating dynamic content using Ajax, php/Codeigniter, and Javascript. The process includes submitting a form from a view to a controller, fetching data, populating an array, and displaying charts based ...

What are the best practices for utilizing *ngIf?

In my Angular project, I am facing a challenge with using *ngIf. My app.component.html file handles both the login page and the dashboard. I want to hide the dashboard until the user logs in. To achieve this, I decided to use *ngIf. Here is how I implement ...

Issue with passing jQuery cookie between two HTTPS pages

I am attempting to transfer a cookie between two secure HTTPS pages using jQuery cookies. The cookie is initially set on page 1 using this code: $.cookie('name', variable, { expires: 300 , secure:true}); Upon navigating to the next page, I try ...

Retrieve event information from the AlloyUI Scheduler

I am having trouble retrieving events from the Scheduler. After reviewing their documentation, I learned that I need to implement SchedulerEventSupport in order to do so. Here is how I implemented it: var agendaView = new Y.SchedulerAgendaView(); ...

"Unlock the power of Angular.js: Extracting table row data with the click of a checkbox

Can anyone help me with this? I am trying to retrieve all checked data from a table row using Angular.js. Below is my code: <tr ng-repeat="gl in galleryDatas"> <td><input type="checkbox" name=""> {{$index+1}}</td> <td><img ...

Display a thumbnail image using a v-for loop

Looking for help with implementing a photo preview in my code using BootstrapVue. The Vue devtools show that the form-file contains the image, but my 'watch' isn't functioning properly. Any assistance would be greatly appreciated! Here is ...

Incrementing and decrementing a variable within the scope in AngularJS

Objective: When the next/previous button is clicked, the label on the current slide should change to display the next/previous category. View the Category Slider Wireframe for reference. Context: I previously tried a solution called 'Obtain Next/Prev ...

Flexible array for varying results

I'm attempting to display a random selection from two arrays by alternating between them, with no concern for storage capacity. Unfortunately, my code is not functioning correctly and I am unsure why. var male = ["have a shot", "item 2", "item 3"]; ...

Tips for creating a jQuery AJAX function in JavaScript that is triggered by an onclick event

Can anyone help with creating a generic JavaScript function to handle AJAX requests and calling it using 'onclick'? I want to ensure that the loaded Ajax results still work with this function. My setup involves JQuery and PHP, so something like t ...

Expanding the properties of an object dynamically and 'directly' by utilizing `this` in JavaScript/TypeScript

Is it possible to directly add properties from an object "directly" to this of a class in JavaScript/TypeScript, bypassing the need to loop through the object properties and create them manually? I have attempted something like this but it doesn't se ...

A guide to dynamically adding a class based on the content of a variable in Vue.js

I have a situation where I need to pass a variable to a component and use it as a class in a div. However, Vue is adding the variable name instead of its content. So, I am passing the prop color which contains the value red. Desired outcome: <div cla ...

Learning fundamental MVC concepts with Express.JS

Express.js offers a basic framework for implementing the standard MVC development pattern. However, many tutorials I have come across tend to mix controller logic within route files or a global app file. In an ideal scenario: Model - Manages core behavio ...

Creating a javascript variable in c#

Currently, I am working on incorporating the selected index text from a DropDownList into a JavaScript string. My approach involves storing the text in a hidden field and retrieving it through C# to ensure the JavaScript variable retains its value even aft ...

Discovering what is impeding the rendering of a webpage

On a particular website, the server rendering happens quickly but there seems to be a delay on the client side which is causing the HTML to be rendered few seconds later. I suspect it could be due to some setTimeout function or similar; are there any tool ...