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

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

AjaxModalPopup does not appear in Visual Studio 2013

I'm currently working on an asp.net project that involves a master page and content page. Within the content page, there is an ImageButton nested inside a gridview. I am attempting to display a modal popup when the ImageButton is clicked, but unfortun ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Do something with the response data from the jQuery AJAX call when it is

<script> $(document).ready(function(e) { $('.username').change(function(e) { var usr = $('.username').val() if(usr.length >= 4) { $('#status').html('<font><image src="images/loader.gif" / ...

Creating a POST method in AngularJS

Here is the code snippet I am working with: var req = { method: 'POST', url: '/customer', headers: { 'Content-Type': 'application/json' }, data: { test: 'testvalue' } }; $http(re ...

Adding double quotes to arrays in D3.js after using the .map method

Here is the code snippet I am working with: d3.csv("static/data/river.csv", function(data) { var latlongs = data.map(function(d) { return [d.Lat,d.Lng]; }) var lineArray1 = latlongs; console.log(lineArray1); When I view the outpu ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

What is the best way to arrange an array based on two properties using regular expressions?

Below is an array containing items: var myArray = [ {catNum : 'CAT I #4', trackingNumber : 'ORG Cat-123'}, {catNum : 'CAT I #6', trackingNumber : 'ORG Dog-345'}, {catNum : 'CAT I #2', trackingNumber : ...

Consistently shifting the Aframe camera towards the focal point

Is there a way to continuously adjust the view of my Aframe scene based on the current viewing direction? It seems like there are two key components needed for this: (1) obtaining the current viewing direction in the correct format, and (2) creating and u ...

Tips for centering the InputLabel in Material UI?

Upon loading the page, I am looking to have the InputLabel appear as shown in the second picture. However, I haven't been able to find any InputLabel props that achieve this. I attempted using the focused prop, but it didn't give me the desired o ...

Why am I encountering http://localhost:3000/api/auth/error?error=AccessDenied when implementing Google signin in my Next.js application?

Can someone please assist me in resolving an issue I am facing with my NextJs application using Google signin? Whenever I try to sign in, I get the error message "http://localhost:3000/api/auth/error?error=AccessDenied". Why is this happening? Here is a ...

Exploring the properties and methods of a node.js module object through iteration

Looking to compile a comprehensive list of all the Properties and Methods associated with the os Node.js module. One possible method is: var os = require('os'); Object.keys(os); Object.getOwnPropertyNames(os); Given that the os module is an Obj ...

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

Dealing with Android Woes: Troubleshooting POST Requests using $.ajax with PhoneGap 2.6 and Zepto.js

Currently, I am working on a PhoneGap application that needs to send a POST request to a Django server. Unfortunately, instead of receiving the expected JSON object with a 401 (unauthorized) response, we are getting a 200 message with no data. Here is a s ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

What are the best ways to stop jQuery events from propagating to ancestor elements?

I have a collection of nested UL's that follow this structure: <ul class="categorySelect" id=""> <li class="selected">Root<span class='catID'>1</span> <ul class="" id=""> <li>First Cat<span ...

Efficiently Parsing for PostgreSQL WHERE Clauses Using AJAX and PHP

Currently, I am facing a situation where I need to retrieve activities with corresponding version numbers. The challenge lies in the fact that some activities have only one version, while others have multiple versions. These activities are obtained through ...

Verify if data already exists in an HTML table column using JavaScript

As a beginner in web programming, I am currently trying to dynamically add data to a table. But before inserting the data into the table, my requirement is to first verify if the data already exists in a specific column, such as the name column. function ...

The importance of .hash in this jquery function explained

I utilized a jQuery function from someone else and tweaked it to fit my needs, however, I am struggling to grasp how it actually operates. Specifically, the line var content = this.hash.replace('/', ''); Can anyone offer an explanation ...