What is the process for obtaining the outcome of an ajax request?

After the request is complete, I want to run specific code.

I'm unsure if this is the correct approach. Can you provide guidance on this?

Thank you!

Handling Ajax Requests

function sendRequest(url, data, type) {
    return $.ajax({
        url: url,
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        type: type
    }).done(function (data) {
        console.log('success');
        return true;
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log('fail');
        return false;
    });
}

Making an Ajax Call

function newAuthor() {
    var data = {
        "last_name": $("#authorLastName").val(),
        "first_name": $("#authorFirstName").val()
    };
    var result = sendRequest('/authors/', data, "POST");
    if(result) {
        // do something if true
    }
    else {
        // do something if false
    }
}

Answer №1

To simplify the process, you can utilize Async/await

async function createNewAuthor() {
    var data = {
        "name": $("#authorName").val(),
        "surname": $("#authorSurname").val()
    };
    var result = await sendRequest('/authors/', data, "POST");
    if(result) {
        // do something if true
    }
    else {
        // do something if false
    }
}

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

Ways to navigate by percentage in react

I'm working on a flexbox that scrolls horizontally with boxes set to 25% width. Currently, I have it scrolling by 420px which is causing responsive issues. Is there a way to implement the scroll using percentages instead of fixed pixel values in React ...

Retrieving User Input for Column Filters in AG-Grid-React

After the user enters input in the column filter, I am attempting to update the Redux mode, but it does not seem to be working properly. <AgGridReact rowData={rowData} columnDefs={columnDefs} defaultColDef={defaultColDef} animateRows={ ...

DirectionsLight isn't functioning properly in Three.js

I attempted to add lighting in Three.js, but after updating the display, the light didn't seem to affect my cylinder. I simply copied and pasted the source code from the Three.js documentation Three.js as instructed, but to no avail. Below is the cod ...

Searching in React can be done dynamically by referencing an array, similar to how the "LIKE" function works in SQL

Currently, I'm tackling an issue with a dropdown feature. My goal is to have the dropdown results sorted when the user enters something into the input field. The values in the dropdown are sourced from an array. For instance, codeList = [N1, N2, N3, ...

Incorporating a for loop, ExpressJS and Mongoose repeatedly utilize the create method to generate

When users input tags separated by commas on my website, ExpressJS is supposed to search for those tags and create objects if they don't already exist. Currently, I am using a for loop to iterate through an array of tags, but only one object is being ...

Using AJAX to showcase information from a web API in organized table formats

Looking for guidance on integrating a web API from the URL "" using jQuery AJAX to populate a table. I've searched for tutorials without much success. ...

Error encountered in Vue3: An uncaught TypeError occurred when attempting to "set" a property called 'NewTodo' on a proxy object, as the trap function returned a falsish

I encountered an error message: Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'NewTodo' This error occurs when attempting to reset the input text value within a child component (FormAddTodo.vue). App.vue: expo ...

Comparing Two Items between Two Arrays

I have a scenario where I need to compare values in two arrays by running a condition. The data is pulled from a spreadsheet, and if the condition is met, I want to copy the respective data. For instance, I aim to compare two cells within a spreadsheet - ...

Guide to playing a gif solely through an onclick event using JavaScript

Below you will find a code that is used to load a gif animation from an array of characters, and then display it within a board class using the image src. I am looking to make the gif animation play only when the displayed gif is clicked. Currently, the ...

Tips for sending a successful POST request with the MEAN stack

Currently, I am utilizing yeoman to set up a new project. My ultimate goal is to master the process of scaffolding CRUD operations. However, I have encountered an issue with a post request. For this reason, I opted for the angular-fullstack generator as I ...

Executing jQuery's $when.apply() function triggers the "then()" method for every individual request that has

Below is a custom jQuery method that I've implemented within an ASP.NET MVC Razor view. The main objective of this function is: Select textAreas Send out an array of ajax requests Display an alert dialog once all ajax requests are completed The cod ...

Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error. https://i.sstatic.net/0Liqi.jpg I have designed a visually appealing travel landing pag ...

What is the standard error function used for jQuery promises?

Is there a way to establish a default error handling function for a jQuery promise? I am running a series of functions asynchronously, and if any of them encounter an error, I want the error to be reported. Currently, this is how I have to handle it: fun ...

Creating a POST Endpoint in Express JS

Hey there! Can someone help me out with creating a basic login script for an app using Express JS? I've been working on a POST function to handle this task, but unfortunately, when I try to echo back the parameters being passed (testing via Postman), ...

What is the correct location for me to store a text file so that AJAX can access it successfully?

After diving into a textbook to learn AJAX, I encountered an introductory exercise that required running some code. However, on line 16, there seems to be an issue with a GET request to retrieve a .txt file. Where exactly should I place the text file - i ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

What happens to the arrays within my function?

I am working on a controller code: public function getChartData(){ $result["categories"] = array(); $result["series"] = array(); $sales = $this->db->Execute("select id_tenant, nama_kantin, count(id_penjualan) as jumlah_penjualan, s ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

Preventing Browser Back Button Functionality in Angular 2

I'm currently working on an Angular 2 website and wondering if there is a way to either disable or trigger the browser's back button using Angular 2. Any insights would be greatly appreciated! ...

Making a Connection with Ajax in Django: Adding Friends

I have been exploring the capabilities of Django-Friends My goal is to make it so that when a user clicks on the add friend button, it either disappears or changes to say "Request sent". However, I am encountering an issue where the button does not disapp ...