Trouble with Global Variable Allocation in jQuery Ajax

I've got a script that includes a jQuery Ajax call:

<script type="text/javascript">
 $(document).ready(function() {
  var timer;
  $.ajax({
     type: 'POST',
         url: 'closettime.php',
         success: function( res ){
         var json = JSON.parse(res);
             timer = json["datecounter"];
             alert(timer);
         }
    });   
 var date = new Date(timer);
 var now   = new Date();                
 var diff  = date.getTime()/1000 - now.getTime()/1000;
 var clock = $('.clock').FlipClock(diff, {
    clockFace: 'HourlyCounter',
    countdown: true,
    showSeconds: true
 });

});
</script>

However, I'm facing an issue where I can't assign the time value in var date = new Date(timer); within the ajax success callback as

timer = json["datecounter"];

Could someone please advise me on how to solve this problem? Thank you.

Answer №1

It seems like the issue may lie in the timing of when the request completes compared to when the code assigning your date variable finishes execution. This can create the illusion that the timer is not being assigned properly. To resolve this, ensure that all code dependent on the timer variable is placed inside the callback function. By making this adjustment, you should be able to address at least one of the issues you are facing.

<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
       type: 'POST',
       url: 'closettime.php',
       success: function( res ){
           var json = JSON.parse(res);
           var timer = json["datecounter"];
           alert(timer);
           var date = new Date(timer);
           var now   = new Date();                
           var diff  = date.getTime()/1000 - now.getTime()/1000;
           var clock = $('.clock').FlipClock(diff, {
              clockFace: 'HourlyCounter',
              countdown: true,
              showSeconds: true
           });
       }
    });
});
</script>

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

Looking to adjust the title font size when exporting DataTable to Excel?

Would like to customize the title of an excel file exported from Datatable. I attempted to implement a solution found on a stackoverflow post, but it ended up applying the customization to the entire sheet. $("#datatable").DataTable({ ...

What is the method for specifying a null value in Typescript?

I'm curious if this code snippet is accurate, or if there's a better way to define it. Is there an alternative to using error!? I'm unsure of its meaning and would appreciate clarification. ...

Cannot locate element using React Testing Library with the selector: [data-testid="task"]

I've encountered an issue while testing a Task component that should be rendered after submitting a form. I'm utilizing redux-toolkit, but despite setting data-testid="task" for the Task component, it doesn't appear in the test DOM ...

Error: The integer provided in the Stripe payment form is invalid in the

I'm encountering an error that I can't seem to figure out. I believe I'm following the documentation correctly, but Stripe is not able to recognize the value. Have I overlooked something important here? https://stripe.com/docs/api/payment_i ...

Tips on emphasizing all div elements and incorporating navigation to each of them

I am seeking a method to enhance a div with highlighting when there is a click or mouseover event. For instance, changing or adding a border color using JavaScript on click or mouseover is straightforward. Recently, I have been contemplating the idea of a ...

jQuery UI Sortable: Efficiently Drag Items Across Multiple Interconnected Lists

One feature of using jQuery UI Sortable is the ability to make the sortable item container scroll when an item is dragged. This can be achieved by specifying the scroll option. In my case, I have several sortable lists that are connected within separate c ...

I possess an array with a specific structure that I wish to substitute the keys as demonstrated below

The data array is currently structured in this way. I have attempted various methods but have not been able to find a suitable solution. I need to send the JSON below via an AJAX request, however, I do not want the keys 0 and 1 in both child arrays. [sch ...

What is the process for dynamically updating a variable's state within a render function?

I'm currently working on a project for my class where we are tasked with creating a website using React. Unfortunately, neither myself nor my group members have been able to figure out how to render a function in a variable state and make it dynamic. ...

Having trouble including a YouTube iframe code within the document ready function

I am having trouble getting the youtube iframe API code to work properly within my $(document).ready() function. When I try to add the code inside the function, the player does not load. However, when I move the code outside of the document.ready, the play ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...

Experiencing an issue with Handsontable: Every time I try to run the countRows method, all I get is "undefined."

Greetings everyone! I appreciate you taking the time to read about my issue. I've been using the handsontable library for a week now and have encountered some difficulties with certain methods. Within a function, I have the following code: count = $ ...

How can I adjust the animation speed for ChartJS graphics?

Trying to adjust the animation speed of a pie chart in chartJS. Various methods have been attempted: numSteps: Number animationSteps: Number Chart.defaults.global.animationSteps = Number However, none of these approaches have successfully altere ...

Is it possible to pass multiple parameters in one onClick event?

My search bar is located below. Upon clicking the 'search' button, I wish for it to update results and redirect to a different page simultaneously. function SearchBar(props) {   const [innerSearch, setInnerSearch] = useState(""); ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...

Troubleshooting issue with parsing MySQL data in HTML table using Node.js

Seeking Assistance! I am currently in the process of developing a node file that displays data from MySQL on an HTML page with a search bar. My issue is that sometimes when I run the code, enter something into the search bar and hit the button, it works s ...

Stopping Popups in Chrome When Printing with JavaScript

Javascript function printPage(htmlPageContent) { var newWindow = window.open("about:blank"); newWindow.document.write(htmlPageContent); newWindow.print(); } In this code snippet, we are creating a new window 'newWindow' and then using ...

Tips for integrating dynamic JSON data with Retrofit in Android applications?

My current project involves developing an app that presents daily stock data to the user. However, I am facing a challenge with using retrofit for API calls due to the structure of the JSON response. It seems impractical to create a POJO for each individua ...

Develop a JSON object containing a JSON array within an Android application

"ORDERDETAIL":[ { "Description":"xyz", "Quantity":"3", "Unit Price":"55", "No.":"7", "Line No.":"30", "Document Type":"2", "Document No.":"105" }, { "Description":"abc", "Quantity":"8", "Unit Price":"12", "No.":" ...

Issue encountered while trying to retrieve JSON data

I am currently using JSON in my application, but I encountered an error. Error: org.json.JSONException: Value {"date":"","shirota":"53.5254","dolgota":"49.1684","imei":"44fd02f38e4a5c0c"} of type org.json.JSONObject cannot be converted to JSONArray" This ...

Creating a new row does not result in the creation of a new span displaying the character count message

Every description field should have its own character counter, with different SpanIDs displayed in respective SpanIds for each new row. How can this be achieved? <div class="row"> <div class="col-s ...