Remaking the functionality of jQuery's $.ajax() method while utilizing the .done() method

As a junior javascript developer, I am working on creating my own "basic" javascript framework inspired by jQuery. I am particularly fond of method chaining instead of callbacks, but I am finding it challenging to implement this.

Currently, I have developed my own version of an ajax "class", but I am struggling to replicate the functionality of .done() used in jQuery.

My goal is to have a syntax like this to eliminate callback hell:

ajax(url, type, data).success(function(response){});

However, when I try this, the response ends up being false because it is called before the ajax request is complete.

I attempted to implement a promise, but I encountered syntax errors and vague error messages like uncaught (in promise) OK.

This is the current state of my code:

// Code snippet

-- My serialize function:

// Code snippet

-- NOTE:

I am aiming to use the ajax function in this manner:

ajax(url, type, data).success(function(response){
  // Handle responseData before the callback
  // On success
}).error(function(error){
  // On error
});

-- This does not necessarily have to involve promises. Any alternative methods are acceptable, as I am open to exploring different approaches.

Answer №1

Here is an example of how promises can be used. In this scenario, the ajax function would return a promise instead of being a constructor. The method used to chain promises is called then.

var ajax = function(url, method, data) {
    return new Promise(function (resolve, reject) {
        var xhttp = new XMLHttpRequest(),
            strType = method.toLowerCase(),
            methods = {
                get: function() {
                    var urlParams = serialize(data);
                    xhttp.open("GET", url + urlParams);
                }
            };
        methods[strType]();
        xhttp.send();
        xhttp.onreadystatechange = function() {
            if (this.readyState !== 4) return;
            resolve(this.status == 200 ? this.responseText : this.statusText);
        };
        xhttp.onerror = xhttp.onabort = reject;
    });
};

//Example function call;
ajax('http://httpstat.us/200?sleep=200', 'GET', {
    'Testval': 'testvalue',
    'field': 'value'
}).then(function(response) {
    console.log("Response is:" + response);
}).catch(function() {
    console.log("There was an error or the request was aborted.");
});

function serialize(obj, prefix) {
    var str = [], p;
    for(p in obj) {
        if(obj.hasOwnProperty(p)) {
            var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
            str.push((v !== null && typeof v === "object") ?
                serialize(v, k) :
                encodeURIComponent(k) + "=" + encodeURIComponent(v));
        }
    }
    return '?' + str.join("&");
};

If you want to use the name success instead of then, you can do the following:

    var promise = new Promise(function (resolve, reject) {
        // ...etc
    });
    promise.success = promise.then;
    promise.error = promise.catch;
    return promise;

:-) Keep in mind that using non-standard method names for promises may not be the best practice. It's recommended to stick with standard promise methods for consistency.

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 extracting the image URL from my JSON string

I am in possession of a json file that includes URLs for images, and I have come across something that seems to be a URL, which is encoded as: iVBORw0KGgoAAAANSUhEUgAAADYAAAAzCAMAAADrVgtcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6m ...

NextAuth: JWT callback that returns an object

I've been working on a project using Next.js (11.1.2) + NextAuth (^4.0.5) + Strapi(3.6.8). The Next Auth credentials provider is functioning correctly. However, I need to access certain user information using the session. I attempted to do this by ut ...

Issue with useEffect EventListener in REACT HOOKS

Recently, I attempted to create a simple Snake-Game using REACT. Everything was going smoothly until I encountered an issue with using useEffect for moving the "snake" when a keydown event is triggered. The challenge arose when trying to implement moveSnak ...

Encountering an issue in Laravel when trying to retrieve data using relationships and the paginate() method

When I try to fetch data using paginate(10), Vue.js does not work. However, if I use paginate(5), it works fine. The code in the Controller with relationships in the model files is working fine and returns a 200 OK response. $results = Posts::with([' ...

Images cascading like a downpour on a canvas (Javascript)

I have been experimenting with canvas, attempting to create a simulation of random falling objects. I've successfully drawn the background image, but I'm having trouble with the second image that is supposed to simulate a rain drop. I've ma ...

Synchronization-free API and callback functions

I am in need of utilizing an asynchronous service. My current approach involves sending data to this service using PHP and CURL, as well as receiving data from a URL provided by the service. How can I effectively respond or wait for feedback from this serv ...

Secure JSON data by transmitting it safely to the front end within a Node.js environment

Currently, I am in the process of building an e-commerce application using NodeJs, Express, and MongoDB. The challenge I am facing is deciding how to securely pass JSON objects from the back end to the front end without compromising data security. Initiall ...

A different component experiences an issue where Angular Promise is returning undefined

This is the carComponent.ts file containing the following method: async Download() { try { const settings = { kit: true, tyres: true, serviced: false, }; const [kits, tyres] = await Promise.all([ this.c ...

Generate a highcharts graph by utilizing AJAX and JSON data

I'm currently working on a website project that involves utilizing the Highcharts library to showcase a single line series chart. To obtain historical financial data, I have implemented AJAX to fetch information from yahoo finance using their YQL. Su ...

Ways to display numerous cards on individual Carousel slides using react-bootstrap

Currently, I am utilizing react-bootstrap to handle my data from an API, which is stored in an array called recipes. My challenge lies in attempting to display 3 items on each slide of a Carousel using react-bootstrap. As of now, each item is appearing on ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

Can Colorbox be configured to load specific sections of a page instead of the entire page?

After coming across this query, I've been experimenting with loading only a section of a webpage using colorbox. My current code setup is as follows: within my webpage, there's a wide array of content, but it also includes a specific div identifi ...

The presence of a default value within an Angular ControlValueAccessor triggers the dirty state due to

My task is to create dynamic Input components for a template driven form using a directive. The default value of the Input component should be set by the component itself. However, I encountered an issue where setting a default value automatically marks t ...

Navigating with Angular and Express

Currently, my Angular project is configured with Express serving my index.html file. As the project progressed, I found the need for a landing page that requires some functionality from the index.html file, such as form input that triggers an API call. H ...

Unable to locate module with React and Material-UI integration

When attempting to implement a Material button in my React app, I encountered the following error: Failed to compile. ./node_modules/@material-ui/core/styles/index.js Module not found: Can't resolve '/Users/hugovillalobos/Documents/Code/Lumiere ...

Trouble with feedback form not showing up

I've been working on creating an ajax feedback form, but I'm facing difficulties in getting it to show up properly. The feedback image appears, but clicking on it doesn't trigger any action. Here's my Form: <div id="feedback"> ...

Console displaying message of comfort twice - ReactJS

I have a simple app that increments the count from 10 to 11 in the componentDidMount life cycle, but for some reason, the numbers 10 and 11 are appearing twice in the console. I would like to understand why this is happening. Here is the code snippet: im ...

What's the purpose of clicking on the page number before accessing the information?

After successfully rendering filtered products, I encountered an issue with implementing pagination. The pagination is functional but requires clicking on a page number before it displays correctly. Even though I have included a loading state, it's no ...

Iterating through a JSON array using the JQuery .each method

Greetings! I'm trying to figure out how to access the msg -> items using jQuery's .each() method. { "msg": [ { "msg_id": "18628", "msg_userid": "12", "msg ...

When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed. Here is the code responsible for this functionality. It identifies the current sibling with the acti ...