Tips for retrieving the posted object in angularJS

My current challenge involves creating an object with a defined name, posting it into a database, and then immediately finding its position and obtaining its id. However, I have noticed that using "get" right after "post" retrieves the data before it's even posted. How can I update the database before retrieving the data? Any suggestions would be greatly appreciated. Thank you!

/*controller createCtrl*/
outbox.controller('createCtrl',function($scope,$http,$filter,$window){
    console.log("In create control.");
    $scope.create = function(name){
        var a=$scope.name;
            console.log(a);
        var newmodel={name:a,};

        /*Post new model*/
        var urlpost = restURL+'/service/repository/models?size=50';
        console.log(urlpost);
        $http.post(urlpost,newmodel)
        .success(function (response, status, headers, config) {
           console.log(status);
           $scope.model = response.data;
          })
        .error(function(response, status, headers, config){
           console.log(response.error_message);
           $scope.error_message = response.error_message;
          });
        /*get the databese*/
        $http.get(urlpost,reqConfig)
        .success(function (response, status, headers, config) {
           console.log(status);
           $scope.models=response.data;
           console.log(response.data);
          console.log(a);
           var w=$filter('filter')(response.data,{name:newmodel.name},true);
           console.log(w);
           var urllink="rootURL+modeler.html?modelId="+w[0].id;
           console.log(urllink);
           $window.open(urllink);
          })
        .error(function(response, status, headers, config){
           console.log(response.error_message);
           $scope.error_message = response.error_message;
          });

    };
});

Answer №1

Start by adding a new entry to your back end system and then immediately retrieve it. Send the newly retrieved data back in the response object.

Avoid making unnecessary duplicate Ajax requests.

Answer №2

Is it necessary to send a get request within the success block of the post request?

/*Create a new model*/
var urlpost = restURL+'/service/repository/models?size=50';
console.log(urlpost);

$http.post(urlpost, newmodel)
    .then(function (response) {
        console.log(response.status);
        $scope.model = response.data;

        /*Retrieve data from the database*/
        return $http.get(urlpost, reqConfig);
    })
    .then(function (response) {
        console.log(response.status);
        $scope.models = response.data;
        console.log(response.data);
        console.log(a);
        var w = $filter('filter')(response.data, {name: newmodel.name}, true);
        console.log(w);
        var urllink = "rootURL+modeler.html?modelId=" + w[0].id;
        console.log(urllink);
        $window.open(urllink);
    })
    .catch(function(response){
        console.log(response.data);
        $scope.error_message = response.data;
    });

Answer №3

I recently shared code that I now realize is too verbose. When using $http.post, the response object can be directly accessed without the need for a filter. For better practice, you can still utilize .success and .error in the following way:

outbox.controller('createCtrl',function($scope,$http,$filter,$window){

    var url = restURL+'/service/repository/models';
    console.log(url);
    $scope.create = function(name){
        if(name==null||name==="undefined"||name==""){
            alert("Model name cannot be empty!")
        }else{
            parent.$.fancybox.close();
            console.log(a);
            var newmodel={name:a,};
            /*Post new model*/
            $http.post(url,newmodel,reqConfig)
            .success(function (response, status, headers, config) {
                 console.log(status);
                 var modelId=response.id;   
                 var urllink="rootURL+modeler.html?modelId="+modelId;
                 console.log(urllink);
                 $window.open(urllink);

            })
           .error(function(response, status, headers, config){
                 console.log(response.error_message);
                 $scope.error_message = response.error_message;
            });
        }//End of else
        };//End of create function
}); //End of controller

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

JavaScript malfunctioning on Chrome

Displayed on the page is a table that lists user details. When the Edit Button is clicked, it allows for the row to be edited. The code provided below works in IE but does not show any response in Chrome. I am looking to make the site compatible with bot ...

Experiencing problems with the Datepicker and cloning functionality in JQuery?

This is the section of code responsible for cloning in JavaScript. $(document).on("click", ".add_income", function () { $('.incomes:last').clone(true).insertAfter('.incomes:last'); $(".incomes:last").find(".income_date_containe ...

Several validation checks - logic malfunction

I have implemented a validation feature for passwords on a form, but I suspect there may be a logic error in my code that I haven't caught yet (blame it on the coffee machine!). Take a look at the JavaScript below: <script type="text/javascript"& ...

Unusual functionality when using ng-selected and ng-repeat in AngularJS

Take a look at this code snippet <!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <title>Sample - static-select-production-example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/ ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...

What is the best way to execute Jest tests concurrently using the VSCode extension?

Running the Jest tests in band is essential to prevent errors from occurring. However, I am unsure of how to resolve this issue. The tests run smoothly when executed through the command line. ...

Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2. Prior to integrating the Table component, my code looked like this: companyList <script setup> import { com ...

Guide to using AJAX for the GraphHopper Matrix API

I am struggling to send this JSON with the required information because I keep encountering an error during the request. message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8" status: "finished" I'm not sure what I&apos ...

The alert feature does not seem to be functioning properly when displaying error messages

// Issue: Alert is not working on error message. I intend to only display up to four issues, after that it should not work. success: function(msg, String, jqXHR) { window.location = 'home.html'; $("#result").html(msg, String, jqX ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

Locate all the properties that are empty within each object contained in a JavaScript array

Consider this scenario: if I were to have an array of JavaScript objects like the following: var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, ...

Converting a variety of form fields containing dynamic values into floating point numbers

Trying to parse the input fields with a specific class has presented a challenge. Only the value of the first field is being parsed and copied to the other fields. https://i.stack.imgur.com/QE9mP.png <?php foreach($income as $inc): ?> <input ty ...

Tips on boosting the speed and user-friendliness of your AJAX/REST application

Exploring the Essential Requirements of an Application I am currently developing a comprehensive application using AngularJS (but it could be any framework). This application interacts with a server built on Google App Engine through REST technology. Th ...

How should one go about creating and revoking a blob in React's useEffect function?

Consider this scenario: import { useEffect, useState, type ReactElement } from 'react'; async function getImage(): Promise<Blob> { // Some random async code const res = await fetch('https://picsum.photos/200'); const blob = ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

What is the best way to notify a user one minute before their cookie expires using PHP and JavaScript?

I need a solution to alert my logged-in users one minute before their cookie expires, allowing them to save content in the CMS. Any ideas on how I can make this happen? In my auth file, I have configured the following: setcookie("USERNAME", $user,time()+ ...

What is NgDocs Provider and how can it be utilized effectively?

I am currently working on creating documentation for a framework within my team and I am trying to incorporate a provider. However, when I add @ngdoc provider, I receive an error message stating: "Don't know how to format @ngdoc: provider" I have lo ...

The issue with AngularJS failing to update input elements on mobile devices

Within my Angular controller's scope, there is an array and a variable used to traverse this array. $scope.items = [ {Name: 'X'}, {Name: 'Y'}, {Name: 'Z'} ]; $scope.currentItemIdx = 0; $scope.currentItem = $s ...

Ways to discreetly conceal forward and backward buttons in the v-pagination component of Vuetify

Is there a way to remove the previous and next buttons from v-pagination in Vuetify? Here's my code snippet- <v-pagination v-model="page" :length="pageCount" :total-visible="8" color="primary" /> ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...