Is there a way to ensure an ajax call finishes executing without relying on 'async: false' or callbacks?

In my view, I have implemented a TypeScript code defining a KnockoutJS binding handler for a clickable element as shown below:

module MyModule {
    export interface ICopyButtonParams {
        dataUrl: string;
    }

    ko.bindingHandlers.copyButton = {
        init: (element: HTMLElement, valueAccessor: () => ICopyButtonParams) => {
            var options: any = ko.utils.unwrapObservable(valueAccessor());
            if (!options.dataUrl) {
                return;
            }

            new Clipboard(element, {
                text: () => {
                    var clipboardData: string;

                    $.ajax({
                        url: options.dataUrl,
                        type: "GET",
                        contentType: "application/json",
                        cache: false,
                        async: false,
                        success: (result: SubmitResult) => {
                            clipboardData = result.Data;
                        }
                    });

                    return clipboardData;
                }
            });
        }
    };
}

The purpose of this binding handler is to enable the clickable element with Clipboard.JS, which allows storing a string in the clipboard upon clicking. In my scenario, I intend to utilize Clipboard.JS's dynamic text feature, where you provide a function that returns the desired clipboard content. Within this function, there is an AJAX call made to an API for fetching the text to be stored.

Due to the architecture constraints, using a standard asynchronous AJAX call with a success callback is not feasible as it may not resolve the clipboard text in time.

To address this issue, I have temporarily resorted to executing my AJAX call asynchronously (not ideal). Since the 'async' flag in JQuery has been deprecated from version 1.8 onwards, I am exploring alternative solutions.

Any suggestions on how to tackle this challenge?

Answer №1

Handling the click event on your own might be a more effective approach.

After your AJAX callback, you can create a textarea, set its value, select it, and then use document.execCommand('copy'), similar to how Clipboard.JS functions (apologies for using JavaScript instead of TypeScript).

ko.bindingHandlers.copyButton = {
  init: function(element, valueAccessor) {
    var url = ko.utils.unwrapObservable(valueAccessor());

    $(element).click(function() {
      $.ajax({
        url: url,
        type: "GET",
        contentType: "application/json",
        cache: false,
        async: false,
        success: function(result) {
          var ta = document.createElement('textarea');
          document.body.appendChild(ta);
          ta.value = result;
          ta.select();
          var r = document.createRange();
          r.selectNode(ta);
          document.getSelection().addRange(r);
          document.execCommand('copy');
          document.body.removeChild(ta);
        }
      });
    });
  }
};

You can check out a similar working example here (without an AJAX request)

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

Tips for saving metadata about properties within a class

I am looking to add metadata to properties within classes, specifically using abbreviations for property names. By using annotations like @shortName(abbreviated), you can label each property as follows: function shortName(shortName: string){ return fu ...

Utilizing MVC architecture and AJAX for seamless form submission

Recently, I delved into exploring MVC on the client side using JavaScript (JavaScript MVC). While everything seemed promising at first, I hit a roadblock when it came to form submissions. The View part couldn't handle it easily. The event is attached ...

Ajax pagination does not update the currently active link

Hello, I am attempting to implement ajax pagination using CodeIgniter. However, I have encountered an issue where the active link in the pagination does not change. Can someone please assist me with this problem? Here is my AJAX code: $(function() { a ...

Get JSON or partial HTML responses from ASP.NET MVC controller actions

Is there a recommended method for creating controller actions that can return either JSON or partial HTML based on a specified parameter? I'm looking for the optimal way to asynchronously retrieve the results in an MVC page. ...

Retrieve data using AJAX and dynamically show it on an element using CodeIgniter

Just to clarify, I am brand new to AJAX and CodeIgniter. I came across this article which seems helpful for beginners like me: My goal is to update an Input Field in a form whenever the select html element changes. <select class="select" name="formul ...

Optimal scenarios for implementing computed/observables in mobx

I understand most of mobx, but I have a question regarding my store setup. In my store, I have an array of objects as observables using TypeScript: class ClientStore { constructor() { this.loadClients(); } @observable private _clients ...

Ways to invoke the function in a separate component

How can I use ViewChild to call a method in a different component? I have a method in the piechart component that I want to access from the app component using ViewChild. In my piechart.component.ts file: export class PiechartComponent { constructor() ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

The value of Angular Input remains unchanged within a FormArray

I am experiencing an issue with the Sequence No in my PreprocessingForm's FormArray. When I add a new row, the Sequence No does not change as expected. <tr class="mat-row" *ngFor="let dynamic of PreprocessingForm.controls.arithmeticI ...

Typescript with Angular: Despite having 7 values in the map, Map.get is returning undefined

Why does Map.get always return undefined when using a number from a form element (extra1) in this code snippet? extraById = new Map<number,Extra>(); @Input() extra1: number = -1; formChanged(carConfigurationFormChanged : any) { const index ...

Exploring project references in TypeScript 3 with distinct `outDir` configurations

I am eager to utilize the project references functionality in TypeScript 3.1. Initially, my project's directory structure post-compilation appears as follows: . ├── A │ ├── a.ts │ ├── dist │ │ ├── A │ │ ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

Encountering an issue with managing promises in Observables for Angular HTTP Interceptor

Currently, I am encountering the following situation: I have developed an authentication service using Angular/Fire with Firebase authentication. The authentication service is expected to return the ID token through the idToken observable from Angular/Fir ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file: subscribeUser() ...

Encountering an unanticipated DOMException after transitioning to Angular 13

My Angular project is utilizing Bootstrap 4.6.2. One of the components features a table with ngb-accordion, which was functioning properly until I upgraded the project to Angular 13. Upon accessing the page containing the accordion in Angular 13, I encount ...

Casting types of objects in Angular2 using TypeScript

Trying to extract the model object from the JSON obtained through a http response call. The following JSON represents the body of the http response, { "dataType": "RWSupplier", "partyName": "Lifecare Pharmaceuticals", "partyShortName": null, "partySecon ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

Having trouble retrieving data from the json file

Using Ajax to obtain a JSON update: $(document).ready(function(){ $('form').submit(function(event){ event.preventDefault(); var form = JSON.stringify($('form').serializeArray()); $.ajax ({ u ...

Understanding how to properly handle the data sent by an ajax request in a NodeJS server

I currently have an array called passedWord = ['a', 'bbb']. I am then making an AJAX request to send this array to a Node.js server. Upon receiving the array on the server, Body Parser returns the following object: { name: 'abc&ap ...