If the AJAX call is successful, proceed with the desired action

Currently, I am utilizing an AJAX call to retrieve data from a PHP file in JSON format. My goal is to change the color of my element based on whether a certain part of the data is true.

I attempted to implement it as suggested here (async:false): Submit form if ajax validator returns true using jquery

Regrettably, the approach did not yield the expected results.

$.ajax({ 
  url: 'preveri.php',
  data: {
    "row": row, 
    "col": col
  },
  type: 'GET',
  dataType: 'json',
  async: false,
  success: function( data ){
    var jsonstuff = data;
    var trys = data.trys[0];
    var result = data.result[0];
    var finished = data.finished[0];

    if (result == "true") {
      $(this).attr("style", "background-color: green");
    } else {
      $(this).attr("style", "background-color: red");
    }
  }
});

Prior to the AJAX call, I verified that this method indeed works:

$(this).attr("style", "background-color:red");

Moreover, attempts were made by replacing this with the ID of the element but the outcome was still unsatisfactory. Another strategy involved making result a global variable and applying the if-else statement after AJAX execution.

The PHP-generated JSON data consists of:

$data = array();
$data['result'] = array($Result);
$data['trys'] = array($trys);
$data['finished'] = array($finished);
$myJSON =  json_encode($data);

Answer №1

To start off, make sure you define $(this) as a global variable and then test out the code below:

var this_var =$(this);
$.ajax({ 
url: 'check.php',
data: {"row": row,"col": col},
type: 'GET',
dataType: 'json',
success: function( data ){
var jsonstuff = data;
var attempts = data.attempts[0];
var result = data.result[0];
var finished = data.finished[0];
 if (result == "true") {this_var.css("background-color","green");} else {this_var.css("background-color","red");}}});

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

The text next to images is being clipped (is it CSS?)

Encountering a problem with CSS on my Wordpress websites. Using WP's editor to float images to the right or left of text, I noticed an issue when viewed on mobile: https://i.sstatic.net/gVFRq.jpg The text gets cut off. How can I ensure that no tex ...

Design a sleek and modern form using Bootstrap 4 that mirrors the aesthetics of the forms found in Bootstrap 3

Is there a way to create a form using BootStrap 4 that resembles the easily customizable forms from BootStrap 3? I am looking to have a bold, right-aligned label within a specific column size (e.g. col-sm-4), with an input field next to it whose width is c ...

Consolidate duplicate list entries and adjust the CSS as needed

Imagine I have an array like this: myarray = ["apple", "apple", "apple", "potato", "apple"]; myarray = ["apple", "apple", "apple", "potato", "apple"]; function listCreate(data) { var output = '<ul>'; $.each ...

Transform a JSON string into a JSONArray

As I attempt to generate test data using a JSON String, the process encounters an issue when attempting to convert the string into a JSONArray resulting in a failed test. String JSONString = "{\"Info\":[{\"area\":301336,\"nati ...

What are the steps for manipulating this string and merging together the values associated with duplicate keys?

In my possession is a string structured as an array of objects. var str_obj = `[ { "STUDENT_ID": "ST001", "MAJOR": "SCIENCE", "STATUS": "1" }, { "STUDENT_ID": "ST002", "MAJOR": "SCIENCE", "STATUS ...

Revolutionary AJAX technology seamlessly updates and refreshes elements within every row or form on a webpage

<script type="text/javascript"> $(document).ready(function() { $("#submit<?php echo $resultshome['hskid']; ?>").click(function() { $.ajax({ type : "POST", url : "/scores/printPOST.php", data : { "subro ...

"Enhance your JavaScript skills with the power of jQuery

I am currently facing an issue where I need to retrieve the value of the normaltagCmt element: <div id="random no"> <div id="normaltagdialog"> <table style="width:100%; height:100%" border="2px"> <tr style="width:100%; height: ...

Are there any alternatives to Google Charts for creating charts?

There is a restriction of only 2k queries per month, which I find insufficient. Are there any alternative classes, plugins, or tools that can be used to generate charts similar to those created by Google Charts? Thank you. ...

tips for changing a json string into yaml format

I am facing an issue with the given code snippet: string stringXDoc = JsonConvert.SerializeObject(ConnectedItemOperations.GetConnectedItemById(id).Edits.EditableData); var json = JsonConvert.DeserializeObject(stringXDoc); The specific file is triggeri ...

Gradient transition effect changing background color from bottom to top

I am facing an issue where I have a block and I want the background color to animate from bottom to top on hover. Can you please help me identify what is causing this problem? Your assistance is greatly appreciated. .right-block--wrapper { backgroun ...

Step-by-step guide to retrieve JSON data from VARCHAR field in Snowflake

I am working with a VARCHAR column that stores JSON data. Here's an example row: { "id": null, "ci": null, "mr": null, "meta_data": { "product": { "product_id": "123xyz", "sales": ...

What steps can I take to successfully implement Tailwind CSS's max-w class?

After successfully using the proper class for setting max width in tailwind, it suddenly stopped working. I'm baffled by the fact that the max-w has refused to take effect. <section class="max-w-[80em]"></section> Previously, I ...

How to activate a hyperlink without being taken to a new page

I have a variety of products stored in a mySQL database, and I am currently retrieving their links through the use of $producturl in my script. These URLs are designed to add the product to the shopping cart (http://www.example.com/cart/?add-to-cart=1127). ...

What is the best way to add additional buttons to my React App after the initial button has been clicked?

Currently, I am in the process of developing a CSV file loader that converts data into JSON format. The loader will consist of three buttons: 1. The first button allows me to select a file from my computer and load the CSV data for conversion to JSON. 2. ...

Bootstrap 4 carousel is experiencing issues with the hasClass function

I'm working on a simple narrowcasting setup using a Bootstrap 4 carousel. Some of the slides in the carousel feature images, while others have Youtube videos embedded. My goal is to automatically play the Youtube video when its corresponding slide be ...

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...

Is there a way to adjust the placement of the .container element?

I am currently working on building a website for educational purposes. My goal is to have a "Follow us" h2 heading with YouTube and Twitter icons positioned on the right side of the page. If the webpage size reduces or if accessed on a mobile device, I wa ...

Is there a way for me to accurately obtain those values?

If I have received this output from the Chrome console log, how can I extract those specific values? Is there a way to retrieve the value following the first ":" character? (Note that sometimes there may be ":" within a URL value - is there a method to fil ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...