Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32'];

    $('.grooveTable').on('click','td', function(){
    color = $(this).data('color') == undefined ? 0 : $(this).data('color')*2;

        // Get Url Parameter

        var result = [];
        window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
        function(str, key, value) {
            result[key] = value;
        });

    $.ajax({
    url: '" . yii\helpers\Url::toRoute("area-chart/change-area-status") . "',
    dataType: 'json',
    method: 'GET',
    data: {areaCodeId : $(this).attr('id'),colourCode:color, location:result['tion%5D'],
    company_code:result['ny_code%5D'],division_code:result['rt%5Bdivision_code%5D']},
    success: function (data, textStatus, jqXHR) {
    statusCheck = data;
    drawChart(data.idCompleted, data.idPending, data.idStarted);
    },});

        if(textStatus == 'SUCCESS' && color == undefined || color == colorArray.length ){

                $(this).css('background-color',colorArray[0]);
                $(this).data('color','0');

        }else if(textStatus == 'SUCCESS' == 'UPDATE'){

                $(this).css('background-color',colorArray[color+1]);
                $(this).data('color',color+1);

        }

});");

Answer №1

When using ajax, remember that it is asynchronous. Make sure to pass the necessary parameters to your functions.

$.ajax({
    url: '" . yii\helpers\Url::toRoute("area-chart/change-area-status") . "',
    dataType: 'json',
    method: 'GET',
    data: {
        areaCodeId: $(this).attr('id'), colourCode: color, location: result['tion%5D'],
        company_code: result['ny_code%5D'], division_code: result['rt%5Bdivision_code%]']
    },
    success: function (data, textStatus, jqXHR) {
        drawChart(data.idCompleted, data.idPending, data.idStarted);
        doSomething(textStatus);
    },
});


function doSomething(textStatus){
    if(textStatus == 'SUCCESS' && color == undefined || color == colorArray.length ){

        $(this).css('background-color',colorArray[0]);
        $(this).data('color','0');

    }else if(textStatus == 'SUCCESS'){

        $(this).css('background-color',colorArray[color+1]);
        $(this).data('color',color+1);

    }
}

Answer №2

Here is the code you can try:

   $.ajax({
  url: '" . yii\helpers\Url::toRoute("area-chart/change-area-status") . "',
  dataType: 'json',
  method: 'GET',
  data: {
    areaCodeId: $(this).attr('id'),
    colourCode: color,
    location: result['tion%5D'],
    company_code: result['ny_code%5D'],
    division_code: result['rt%5Bdivision_code%5D']
  },
  success: function(data, textStatus, jqXHR) {
    drawChart(data.idCompleted, data.idPending, data.idStarted);
updatebackground($(this),textStatus, color, colorArray); // call function here
  },
});

It's advisable to move all the code to a separate function like so:

funtion updatebackground(element,textStatus, color, colorArray){
if (textStatus == 'SUCCESS' && color == undefined || color == colorArray.length) {

  element.css('background-color', colorArray[0]);
  element.data('color', '0');

} else if (textStatus == 'SUCCESS') {

  element.css('background-color', colorArray[color + 1]);
  element.data('color', color + 1);

}
}

Thank you,

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

Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts export const validateRequest = cache( async (): Promise< { use ...

Generate an XML document on the server with the help of SimpleXML and jQuery Ajax technology

I am facing a challenge in achieving my goal, which involves creating an XML file using an Ajax call. The code snippet below demonstrates my attempt at this, although it may not function correctly: HTML <html> <head> <!-- Including JQuery ...

Waiting for completion of all nested AJAX and each calls in jQuery

I am facing an issue with my JavaScript code where a particular section is not running to completion before moving on. The problem lies within nested each loops inside ajax calls, causing delays in execution. Whenever I test this in Chrome and set a break ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

Leveraging an external script for enhanced functionality in React/Meteor application

I'm currently facing a challenge incorporating an external script into my React component within Meteor. I've experimented with directly placing the script tag in my component as follows: TheLounge = React.createClass({ render() { return ( ...

Tips for retrieving return values from AJAX URL content

As I am writing some code to send data from one page to another through the ajax URL, I encountered an issue where the retrieved values on the previous page are showing as null. The first page code looks like this: <script> function myFunction() { ...

Improving user input in AngularJS

My goal is to create a filter that converts time into seconds, such as: 01:30:10 becomes 5410, and vice versa. This way, the model only holds seconds while providing users with a more user-friendly representation. I've successfully implemented a work ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

Encountering the error message "Uncaught TypeError: Cannot read property 'addEventListener' of null with querySelector

I attempted using getElementsByClassName but encountered the same error, which is peculiar. I had to change <p id="trigger-overlay"> in my HTML to <p class="trigger-overlay"> error function toggleOverlay(){alert('fire');}; var tri ...

"Utilizing long-polling techniques for cross-subdomain AJAX requests

Currently, I am developing a notifications script that continuously checks a database for any updates and displays them in a custom JavaScript popup. I have successfully implemented the jQuery AJAX loading and processing script as well as the PHP long pol ...

How to create an AngularJS Accordion with dynamic is-open attribute using ng-repeat

Even though I can get it to work without using ng-repeat, the issue arises when I have a list of elements and is-Open doesn't function properly. 1. It should only open one panel at a time (sometimes it opens all) 2. The value of is-Open should be ...

The issue at hand is that one of the JavaScript buttons is functioning properly, while the other is not playing the video as intended. What steps can

I've been working on a script for my school project website that should make buttons play videos, but I'm running into an issue where it only works for the first button (btn). Programming isn't my strong suit, and I put this together based o ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

Utilizing i18n for moment formatting techniques

As I switch from moment to date-fns, I came across this code that involves moment, which I don't quite understand. However, I do comprehend the map function. this.events[0].dates.map(date => moment(date).format(this.$i18n.locale)) I set up an e ...

Connect to a node.js server from a different network

Looking to set up a basic live chat using node.js, socket.io, and express. Managed to get it working on my local network, but wondering if there's a way for someone from another internet connection to connect without me needing to pay for server space ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

What are some strategies for breaking down large components in React?

Picture yourself working on a complex component, with multiple methods to handle a specific task. As you continue developing this component, you may consider refactoring it by breaking it down into smaller parts, resembling molecules composed of atoms (it ...

Crafting personalized objects from an array

In the process of creating an object from an array, I am faced with a dilemma. The elements in the array are as follows: var arr = [ 'find({ qty: { $lt: 20 } } )', 'limit(5)', 'skip(0)' ] Despite my efforts, my code is ...