Utilize AJAX within an Angular method

I am encountering 2 issues with the $http function in this particular code snippet.

$scope.buttonClick = function(){
    // Sending input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.contact = "";
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Following Code
    console.log('Next Code');
}

The first issue I am facing is that when I try to clear a contact, it doesn't happen immediately. It only clears after I press a key into the input field. If I move

$scope.contact = "";

outside of the POST request, it works as expected.

The second problem is why the POST request is being called last. The current output of the code execution is:

Code Next
success

but I would like the output to be:

success
Code Next

Thank you for any suggestions and solutions!

Answer №1

If you are utilizing jQuery for the ajax call outside of the angular environment, it is essential to trigger a digest cycle for the scope to reflect the changes in your view.

To resolve this issue:

$scope.buttonClick = function(){
    // Send input data
        $.post('lib/add_contact.php', $scope.contact, function(data){
            data = angular.fromJson(data);
            if(!data.error){
                $scope.$apply(function(){ //<-- calling $apply()
                    $scope.contact = "";
                });
                console.log('success');
            }else{
                console.log('error');
            }
        });

    // Next Code
    console.log('Next Code');
}

However, the recommended approach would be to utilize the built-in $http service within angular, which automatically triggers the digest cycle as it is aware of angular.

Utilizing $http (don't forget to add it as a dependency to your controller)

$scope.buttonClick = function() {
    $http.post('lib/add_contact.php', $scope.contact).success(function(data) {
        data = angular.fromJson(data);
        if (!data.error) {
            $scope.$apply(function() { //<-- calling $apply()
                $scope.contact = "";
            });
            console.log('success');
        } else {
            console.log('error');
        }
    });
}

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

Sending an object from Rails to Javascript

My MapsController is def show @outlet=OUtlet.all render 'maps/map' end In the view page map.html.erb, I iterate through each outlet to display their latitude and longitude: <% @outlet.each do |product| %> <%= product.latitu ...

"click on the delete button and then hit the addButton

I have created a website where users can save and delete work hours. I am facing an issue where I can save the hours at the beginning, but once I delete them, I cannot save anything anymore. Additionally, when I reload the page, the deleted data reappears. ...

Ruby on Rails: Making an Easy AJAX Call

i am encountering an issue with my ajax request: within my application, i am attempting to set up a basic ranking system. Once configured, whenever I click on the rank button, the page reloads and the rank is refreshed. I need help understanding how to i ...

Accessing object properties using a string for the variable name in Javascript

As I develop a Music composition program in JavaScript, I have encountered a challenge when it comes to iterating through my data quickly. My JSON object, named song, is structured like this: song = {"track0":"data...", "track1":"data...", ...}; I am con ...

Trigger a specific directive instance through a function call when a key is pressed on the

Is it possible to trigger a specific directive instance's function when a global keyboard shortcut is pressed and it has the class "focused" based on ng-class? Below is some template code: home.html <body ng-controller="SampleController"> ...

Display a YouTube video on a webpage using the URL provided by the server

Dealing with a frustrating issue where I can't seem to embed a YouTube video using the URL provided from the database. I've already whitelisted YouTube in my app configuration by app.config(function($sceDelegateProvider) { $sceDelegateProvi ...

What is the process for moving entered data from one text box to another text box when a checkbox is selected?

I need help with a function that reflects data entered in one text box to another text box when a checkbox is ticked. The checkbox is initially checked and the values should change when it is unchecked and then checked again. Currently, the code is only ou ...

Determining Velocity of an Object in Three.js

Can anyone help me figure out how to calculate an object's velocity in three.js? I've checked the Object3D documentation but can't seem to find anything related to velocity. Appreciate any assistance, ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...

Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult. This is what I have so far, but I suspect the issue lies within the h variable. function formatTime(time) { var h = m = s = ...

How can I make an AJAX request in Rails 3 to retrieve an HTML page?

I am experimenting with using Rails to display an .html.erb template via an ajax request under specific conditions. By default, I am consistently receiving the .js.erb file when making an ajax request. Without delving into the reasons behind this choice, ...

Executing multiple PHP scripts or requests in parallel

Our system architecture is set up as follows: Client: Represents a regular client P Server: An apache server acting as a proxy (forwards queries to M Server) M Server: The main server where all the work is done. In our setup, query Q1 differs from que ...

How to remove an event listener that was added within a function in JavaScript?

I am encountering an issue while trying to remove an event listener that was created inside a function. Oddly enough, it works perfectly when I move the event listener outside of the function. See the example below: <body> <div id='myDiv&apo ...

Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this (source: statcan.gc.ca) However, I am facing an issue as I am unable to display two sets of data for comparison. Following a tutorial from , I have cr ...

Communicating Progress Updates from C# to Angular 6 Using HttpPost

I'm building an Angular 6 application with a progress bar that displays the rendering and downloading progress of a PDF file as a percentage. Here's my Post call: renderReport(renderObjectId: number): Observable<HttpEvent<Blob>> { ...

How can I dynamically populate a select menu in HTML without the need to submit any data

Looking for help with an input form in HTML that uses a combination of input and select boxes. My goal is to dynamically populate a select menu based on the data entered into the input boxes. For example: Employee One: Jim Employee Two: John Employee Thre ...

Having difficulties integrating a login solution due to an error saying "eslint Promise executor functions should not be async no-async-promise-executor"

I'm currently working on integrating a login solution into my Vue app using the JWT Authentication plugin. While I have a test solution that is functional, I'm facing an issue in my main branch where the eslint version seems to be causing an err ...

The axios GET request failed to return a defined value

My current issue involves making a get request using the following code snippet: router.get('/marketUpdates',((request, response) => { console.log("market updates"); var data: Order[] axios.get('http://localhost:8082/marketUpdates& ...

AngularJS- Efficiently loading components asynchronously within the application

As I dive into developing my app, I've decided to use AngularJS as my front-end framework. However, my lack of experience with AngularJS has presented me with some challenges in understanding its concepts and logic. Below is a rough outline of the sc ...

What should I do if one of my images fails to load after the previous one has loaded successfully?

My code is designed to create an animation using 3 canvases: one for the base image, one for the streamline wind map drawing, and another for an image covering part of the drawing. The following code displays the uploading of two images. var im ...