Issues Arising from Asynchronous Functionality in jQuery and Javascript

I've hit a wall and can't seem to find a solution in the resources on Stack Overflow or Google. There must be something simple that I'm overlooking, maybe you could offer some help?

Here's the scenario:

  • A JavaScript function is triggered by a click event and adds a new contact to our database.
  • After successful creation, additional functions are called to adjust settings based on checkboxes.
  • These calls are asynchronous, causing only the last function call to update the contact successfully.
  • I can't get the calls to execute sequentially instead of concurrently.
  • Each call returns a JsonResult upon completion (which is needed for other parts of the application).

The current code looks like this:


function CreateClicked() {
  Contact.Create(<strong>**bunch of params**</strong>, function(data) {
    if(data.success) {
          togglePrimary(data.newId);
          toggleBilling(data.newId);
          toggleTechnical(data.newId);
          toggleBalance(data.newId);
          toggleSecurity(data.newId);
          toggleMarketing(data.newId);
          Modal.Load(<strong>**loads a modal view**</strong>);
    }
  });
}

The toggle functions look like this:


function togglePrimary(id) {
  if ($("#contact_admin_primaryrole").prop('checked')) 
     {Contact.TogglePrimaryRole(id);}
}

This invokes a controller function that appears as follows:


public JsonResult TogglePrimaryRole(int contactId) {
try {
var c = new Contact(contactId);
c.IsPrimaryContact = !c.IsPrimaryContact;
c.Update(AuthenticatedUser.Username, !c.IsPrimaryContact);
return Json(JSONResponseFactory.SuccessResponse("Contact updated successfully"));
}
catch (Exception ex) {
return Json(JSONResponseFactory.ErrorResponse(ex.Message));
}
}

How should I structure this so that each toggle function waits for the previous one to finish and return a Json response, regardless of success?

Any suggestions?

Cheers, Dez

Answer №1

Try using jQuery promises for better control:

togglePrimary(data.newId).then(toggleBilling(data.newId)).then(toggleTechnical(data.newId))

You can ensure the next function runs only if the previous one was successful. If you want a function to run regardless of the outcome, use always() instead of then()

togglePrimary(data.newId).always(toggleBilling(data.newId)).always(toggleTechnical(data.newId))

This functionality requires jQuery version 1.6 or newer. To link it from a CDN, use the following code:

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>

Answer №2

After struggling with promises and JavaScript function chaining with callbacks, I decided to transform the status values into arrays of strings and handle the parsing within the controller instead!

Grateful for the assistance :)

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

Emberjs: Optimal approach for managing relationships that are not included in the initial JSON data

I am facing a situation where I have a user JSON api: { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="77241e1914120512371607051e1b59151e0d">[e ...

What is the process for implementing document.ondrop with Firefox?

I'm experiencing an issue where the document.ondrop function seems to be working in Chrome, but not in Firefox. Here's a link to an example demonstrating the problem: In the example, if you try to drop a file onto the page, it should trigger an ...

Animating CSS Pixel Fragments

After applying a simple CSS animation that moves size and box shadows from one side of the screen to the other, I am noticing residual pixel fragments left behind. To see this issue in action on Chrome 66, check out the Code Pen: https://i.sstatic.net/Gl ...

A single user having multiple email addresses registered on the ASP.NET Membership Provider

I am curious about something.. within the ASP.NET membership provider, is it feasible to have a user with multiple email addresses? I am trying to design a page (ASP.NET MVC 3) where users can use different emails to log in. Can this be done? Thank you! ...

Using Dat GUI alongside Three.js to generate 3D text geometry based on user input, with real-time updates

Trying to utilize the combination of Dat GUI and Three.js to allow for user inputted text to generate 3D text geometry that updates in real time. Successfully achieved control over the x, y, and z positions, as well as displaying the text input box. Strug ...

The image file that was uploaded from a React Native iOS application to Azure Blob Storage appears to be corrupted or incomplete as it is not

Struggling to develop a feature in a React Native mobile app where users can upload and crop their profile picture, then store it in Azure blob storage. I encountered difficulty with implementing react-native-fs as many resources recommended it, but I kep ...

What does the underscore before a function in JavaScript or PHP signify?

I am curious about the significance of the underscore symbol (_) when it is placed before a function or variable. Does it serve to simply describe something, or is it required for executing specific functions or calling certain methods? In JavaScript: va ...

Developing child objects using submitted json data in Django: A comprehensive guide

Working on a payment system involves submitting payments to an external rest api (Stripe) and handling the returned "token" object. This token is stored in a hidden HTML field and the form is submitted using jQuery. Following this, a CreateView is used to ...

What is the best way to implement this code using MongoDB's $push and $inc operators?

Having some trouble getting this code to work properly where I use $inc to increase the number of likes and $push to add the userId to the usersLiked array: Sauce.updateOne( { _id: req.params.id }, { ...sauceObject, likes: req.body.like ...

How to efficiently use ng-repeat and toggle filter in AngularJS?

Struggling with creating a filter expression. I am working with an array of documents: [{title: 'doc1', read: false} {title: 'doc2', read: false} {title: 'doc3', read: false} {title: 'doc4', read: true} {title: &ap ...

` How can you output data values using form data? `

I need help with printing form data values using the formData.entries function because I am dealing with multiple ng-repeats. <table class="table table-bordered table-hover"> <thead> <tr> <th>Product Name< ...

Why isn't the callback function for setTimout() working as intended?

Can someone explain why setimout(fun(),time) isn't working in this specific scenario? Explanation: This code displays a message and then hides it. I want to add a delay of 2 seconds before hiding the message, but when I try to do so using setTimeout, ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...

Why is there a rendering error when using a template for an SVG element in Angular?

<html ng-app="vg"> <body> <justsvg width="100" height="25"></justsvg> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ ...

What could be the reason for the absence of the loading sign in Chrome, even though it appears when the code is run on Firefox?

I implemented a function to display a loading screen on my HTML page with Google Maps integration. However, when I called the function popUpLoadingScreen() and dismissLoadingScreen() to show and hide the loading message while rendering map markers, the loa ...

What is the best way to retrieve a specific JSON API item using Python 3.6?

I've been trying to retrieve the values from an API json item named DataClasses, which includes "Dates of birth," "Email addresses," "IP addresses," "Passwords," "Usernames," and "Website activity." Below is the code I have been using: import reques ...

IE throwing an invalid argument error when making an AJAX request

I have a strange issue with my ajax request - it works perfectly fine in all browsers except for IE, specifically IE10! The error message I am encountering in the IE console is as follows: SCRIPT7002: XMLHttpRequest: Network Error 0x80070057, Invalid arg ...

Getting the value of a variable inside an onclick function

I am facing an issue with displaying the values of 2 variables inside an onclick event. I have tried the code below but it is not working. Can someone please help me solve this problem within the next 3 hours? var myCode = "12345"; var myCount = "5" $(&a ...