Obtain the value of a jQuery variable in TypeScript

I'm attempting to utilize the jQuery $ajax() function to call a Web API. After making the call, I am trying to figure out how to store the result in my TypeScript variable.

 $.ajax({
  method: "POST",
  url: 'URL',
  data: { email:'example_email@example.com',
      password:'pass'}

})
.done(function(result) {

  this.response = result;

}) .fail(function(result) {
  this.response = result;
})

Answer №1

In order to assign it to the object initiating the Ajax call, you can utilize an arrow function to grasp the contextual this

class MyCaller {
   response: any;
   doCall() {
      $.ajax({
         method: "POST",
         url: 'URL',
         data: { email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c183f35393134763b373535">[email protected]</a>', password:'pass'}
     }).done((msg ) => {
       // this indicates MyCaller, whereas a basic function would not
       this.response=msg; 
     }).fail((msg) => {
       this.response=msg;
     })     
   }
}

If you are working with TypeScript, you have the option to utilize async and await to streamline your code. The following would be the equivalent:

class MyCaller {
    response: any;
    async doCall() {
        try {
            this.response = await $.ajax({
                method: "POST",
                url: 'URL',
                data: { email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="532736202713343e323a3f7d303c3c">[email protected]</a>', password:'pass'}
            })
        }catch(error) {
            this.response = 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

Transferring information between pages through ajax communication

I am working with two pages named testing.php and submission.php. My goal is to send data from testing.php to be displayed on submission.php. For example, when a user clicks on test1, they should be directed to submission.php where I want to display the te ...

Generate a list of users using Angular in an efficient manner

I am working on creating a user list similar to the image provided below. I am using Angular and Bootstrap for the basics of this project. However, my concern is how to efficiently handle a large number of users. If the user count exceeds 10k, what would b ...

Execute .mts files using ts-node

Can ts-node be used to run .mts files? I attempted to do so, but encountered errors with imports (within the .mts file). Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. I am hesitant t ...

Trouble with Ajax connecting to the wunderground API for weather data retrieval and display

Hey there! I'm currently experimenting with a public api from wunderground (you can find more information at [http://wiki.wunderground.com/index.php/API_-_XML][1]) for use on a web page. I'm actually working on creating a widget for a phone, but ...

Implement rounded corners on D3js Donut Chart

In my AngularJS application, I have successfully implemented a donut chart as shown below: https://i.stack.imgur.com/3GVwN.png However, the design mockup indicates that we would like to achieve this look, with a border-radius property applied to the gree ...

Dynamically populate select options using Spring Boot Ajax technology

Hey everyone, I need some help with populating a select tag with a list of objects in JavaScript. Here's an example of the code: @RequestMapping(value="/getAllIndustries") @ResponseBody public List<IndustryModel>getAllIndustries() { return ...

Trouble with Fancybox 2 and CSS classes not applying correctly

Despite my previous successful experiences with fancybox, I am currently facing an issue where the CSS styling is not being applied as expected. The large images appear grouped correctly, but without any styling, causing them to shift to the right after ap ...

CSS Class Returns to Inactive State

One of my tasks involves adding a new class to an image. .bbbLink img { outline: 1px solid #ddd; border-top: 1px solid #fff; padding: 10px; background: #f0f0f0; } When hovering over the image, I apply the following styles, .bbbLink img ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

Exploring the Angular Checkbox n-Change - is it really all about 'this'?

Looking for a solution with a series of checkboxes: <input type="checkbox" ng-change="??????"> I am trying to figure out how to set $scope.mode.someOtherValue = false when the checkbox is checked. Any ideas on how to extract the checkbox value wi ...

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

Mistake in Timestamp Separation - JavaScript

I have a Timestamp retrieved from MSSQL and displayed on a Webclient. The timestamp reads: Thu Jan 01 18:00:00 CET 1970, however, I am only interested in the time format: 18:00 or 18:00:00 (preferably the former). <script> var timestamp = ...

When the button is clicked, send data using 'POST' method to the php file and fetch

<script> $(document).ready(function(){ $("#vE_rebtn").click(function{ var reverifyEmail = '<?php echo $_SESSION["verifyEmIPv"]; ?>'; $('#rE_rebtn').hide(); $('#re_ ...

Combining multiple template filters in ng-table with the power of CoffeeScript

Combining AngularJS, ng-table, and coffeescript has been quite a task for me. I've been trying to create a multiple template filter within coffeescript and pass it into my angularjs template. One of the challenges I'm facing is with a combined & ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

Creating a JavaScript script to implement a CAPTCHA feature on Google Forms

I'm looking to implement a JavaScript solution that can prevent spam on Google Forms. The idea is as follows: Generate a random number a between 1 and 1000; Generate another random number b between 1 and 1000; Obtain input from the user, storing it a ...

Scrolling jqgrid to focus on the current day column and implementing a blinking effect on cells with stored data

I have a jqgrid with 38 columns of data, where the first 6 columns are frozen and the rest are unfrozen. Depending on the combo box selection, it shows either dates or months (see sample image here). After loading the grid, I want it to automatically scrol ...

Creating a library that relies on Cypress without the need to actually install Cypress

We have adopted the page object pattern in our testing and recently made the decision to move them into a separate npm-published library for reusability. Considering the heavy nature of Cypress and potential version conflicts, we believe it's best no ...

Display email address in a concise manner

Managing user information in my project involves capturing both username and email address. While the username is optional, the email address is mandatory with a maximum length of 100 characters. My issue arises when the email address exceeds 60 character ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...