jqueryangularjsajaxvirtual-machine

Passing VM Variable in Controller to Another Ajax Call


I am currently trying to figure out away to return an ID from my first AJAX call and pass that ID into the second AJAX call. I have set let vm = this. What is the correct way to pass vm.data.id from results.id into the second call?

      vm.retrieveId = () => {
            $.ajax
            ({
                type: "GET",
                url: url,
                dataType: 'jsonp',
                success: function (res) {
                    vm.data = res;
                    console.log(vm.data);
                }
            });

        };

        vm.getPhotos = () => {
            $.ajax
            ({
                type: "GET",
                url: "http://webbtelescope.org/api/v3/image/" + vm.data.id,
                dataType: 'jsonp',
                success: function (res) {
                    let results = res;
                    vm.photos = results;

                }
            });
        }

Solution

  • vm.retrieveId = (callback) => {
        $.ajax({
            type: "GET",
            url: url,
            dataType: 'jsonp',
            success: (res) => res ? callback(res) : console.error("No data returned"),
            error: (xhr, status, error) => console.error("Error retrieving ID:", status, error)
        });
    };
    
    vm.getPhotos = (id) => {
        if (!id) return console.error("Invalid ID");
            $.ajax({
            type: "GET",
            url: `http://webbtelescope.org/api/v3/image/${id}`,
            dataType: 'jsonp',
            success: (res) => res ? (vm.photos = res) : console.error("No photos returned"),
            error: (xhr, status, error) => console.error("Error retrieving photos:", status, error)
        });
    };
    
    vm.retrieveId((data) => data.id ? vm.getPhotos(data.id) : console.error("No valid ID found"));