What is the best way to differentiate and analyze new AJAX output from previous data using div elements?

Embarking on a project to develop a high/low game using JavaScript, I encountered a perplexing issue where the displayed numbers seemed to be out of sync with the variables stored. This discrepancy left me scratching my head as I struggled to get them to align.

UPDATE: After some investigation, I realized that the code executed before the AJAX call was complete, leading to a timing offset. It dawned on me that having the old code available for comparison with the new version proved invaluable in troubleshooting. Hence, I've retained the flawed code and appended the corrected version at the end.

Special thanks to the following resource for helping me find a resolution: Wait for AJAX before continuing through separate function

Original JavaScript:

var y = "0";
var z = "0";
var output_div = document.getElementById("outcome");
var last_ = document.getElementById("val");
var cardVal;

function higher(x) {

  var new_ = last_.innerHTML; //getting new value
  y = last_.getAttribute("data-old"); //getting old value

  console.log("data_old " + y);

  z = ajx(); //calling function return the value from which need to compare
  console.log("data_new " + z);
  if (x === 1) {
    if (z > y) {
      output_div.innerHTML = "Winner!";
    } else {
      output_div.innerHTML = "Loser!";
    }
  } else {
    if (z < y) {
      output_div.innerHTML = "Winner!";
    } else {
      output_div.innerHTML = "Loser!";
    }
  }
  last_.setAttribute("data-old", new_); //setting old value with current value of div

}


function ajx() {
  $.ajax({
    url: "./getfacecard.php",
    success: function(response) {
      var result = $.parseJSON(response);
      var img = result[0];
      cardVal = result[1];
      document.getElementById(\'card\').src = img;
      document.getElementById(\'val\').innerHTML = cardVal;
    }

  });
  return cardVal; // return current card value in calling function

}

Updated Working JavaScript:

var lastVal = document.getElementById("lastVal"); //Last played cars value
var wl = document.getElementById("outcome"); //Shows win or lose
var newVal = document.getElementById("currentVal"); //Current face up card
var iSrc = document.getElementById("card"); //Card img
var lVal; //Last cards value from post
var iLink; //Image link from post
var nVal; //Gets new html to be sent to post.

function start(x){
//  console.log("Start:");

    ajx(function(){ //Runs ajax before continuing 
        iSrc.src = iLink; //Set new card image src
        newVal.innerHTML = nVal; //Sets Current card value in div
        lastVal.innerHTML = lVal; //Sets Last card value in div
//      console.log("-slgn"); //Consoles to track code launch order.
//      console.log("-Last Value: "+lVal);
//      console.log("-Current Value: "+nVal);
//      console.log("-Link: "+iLink);
//      console.log(x);
        if(x===1){ //If clicked higher
            if(nVal>lVal){ //If new card is higher than old card
                wl.innerHTML = "Winner!";
            }else{
                wl.innerHTML = "Loser!"
            }
        }
        if(x===2){
            if(nVal<lVal){ //If new card is lower than old card
                wl.innerHTML = "Winner!";
            }else{
                wl.innerHTML = "Loser!"
            }
        }
    });

}

function ajx(callback) {
  $.ajax({
    type: "POST",
    data: {data:newVal.innerHTML}, //Post new card value to be returned as last card.
    url: "./getfacecard.php",

    success: function(response) {
      var result = $.parseJSON(response);
      iLink = result[0]; //img
      lVal = result[2]; //Last card
      nVal = result[1]; //New Card
//    console.log("ajax");
      callback(); //Go back and the code
    }

  });

}

Answer №1

To streamline your code and only require one div, you can utilize the custom attribute within your div to store both current and old values. Your div should appear as follows:

<div data-old="0" id="val">0</div>

The corresponding js code will look like this:

var y = "0";
var z = "0";
var output_div = document.getElementById("outcome");
var last_ = document.getElementById("val");

function higher(x) {

  var new_ = last_.innerHTML; // retrieving new value
  y = last_.getAttribute("data-old"); // getting old value

  console.log("data_old " + y);

  z = ajx(); // calling function to return value for comparison
  console.log("data_new " + z);
  if (x === 1) {
    if (z > y) {
      output_div.innerHTML = "Winner!";
    } else {
      output_div.innerHTML = "Loser!";
    }
  } else {
    if (z < y) {
      output_div.innerHTML = "Winner!";
    } else {
      output_div.innerHTML = "Loser!";
    }
  }
  last_.setAttribute("data-old", new_); // updating old value with current value of div

}


function ajx() {
  $.ajax({
    url: "./getfacecard.php",
    success: function(response) {
      var result = $.parseJSON(response);
      var img = result[0];
      var cardVal = result[1];
      document.getElementById('card').src = img;
      document.getElementById('val').innerHTML = cardVal;
    }

  });
  return cardVal; // returning current card value from function

}

In the above js code snippet, after the ajax call completes its execution, it will return cardVal which is then assigned to variable

z</code for comparison with <code>y</code (old value) in order to display the desired output. Additionally, returning the value from the ajax call ensures that the updated value is available within the <code>higher
function for further processing.

(This code has been thoroughly tested and performs as expected)

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

Dispose of 3D models automatically when they are no longer in sight

To optimize memory usage in my application, I've implemented a method to dispose of any 3D models that are no longer visible to the camera. This involves checking if the camera can see the position of each model using model.position. The following cod ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

Building a ReactJS application that displays an array of images with a distinct pop-up feature for each image

Having trouble creating unique popups for each image in React. I have a set of 20 images that should be clickable, with only one popup open at a time, each containing text and an image. Currently mapping out the images from an array. Looking for assistan ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

Changing the .load function based on user input

Can I replace a .load text with one that can be updated by a user using form input or similar method? My goal is to create a code that retrieves data using unique div IDs (specific to each employee) containing information within tables across various HTML ...

The NodeJS req.query is providing inaccurate information

When I send a JSON from the Client-Side to a NodeJS Server, it looks like this: $.ajax({ type: "POST", dataType: "jsonp", url: "www.xyz.com/save", data: { designation: "Software Developer", skills: [ "", "ASP.NET", "P ...

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

What is the best way to create a fading footer effect on scroll using jQuery?

Why is my footer not fading in after 1000px like I want it to? Instead, it appears immediately on the screen. I attempted using fadeIn() in jQuery but had no luck. I also tried to make it disappear with fadeOut(), again with no success. Am I missing someth ...

In my attempts to retrieve specific statistics from the PokeAPI using Axios and Node.js, I encountered an error

Having an issue while trying to utilize the Pokemon API. Whenever attempting to access the attack, HP and speed stats, all Pokemons show up as undefined! Can someone please point out what might be wrong with my API call? const axios = require('axios&a ...

Utilizing the Model URL Parameter in VueJS

In the context of , my objective is to dynamically modify a range input element and reflect that change in the URL. // Incorporating URL update with range input manipulation var Hello = Vue.component('Hello', { template: ` <div> &l ...

Chrome browser is experiencing an issue with the Modal RadWindow not closing properly

In my main "Report" page, there are actions available to the user that open a modal RadWindow. The user can then take actions within the modal window, click Save, and the modal window should close while the main grid refreshes. While this functionality wo ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

There seems to be a glitch in the functionality of annotations when using annotator.js

Currently, I am utilizing annotator.js to store the range in mysql. The following code fragment is being used for highlighting text within my file: <script src="/js/pdfjs/annotator.js"></script> <script> $(function(){ var annotation ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

Looking for a resolution with NicEditor - Seeking advice on incorporating custom select options

I recently started using NICInline Editor and found a helpful sample at Is there a way to incorporate custom options into this editor? I would like the selected option's value to be inserted right at the cursor point of the Editor Instance. Query: H ...

How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and ...

Having difficulty executing a function inside a JavaScript file

Within my index.php file, the following lines of code are present: <!doctype html><html class=""><head><title>a title</title> <link href="_css/boilerplate.css" rel="stylesheet" type="text/css"> <script type="text/jav ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

The Response.Write function is not functioning properly in the production environment

I have created a C# WebService (ASMX) with the code snippet below: if (!SomeValidation()) { //context.Response.ContentType = "application/json"; //context.Response.ContentType = "text/plain"; context.Response.ContentType = "application/text"; ...