What is the method to perform an ajax request in JavaScript?

I am currently in the process of developing a dashboard that will feature buttons at the top for accessing monthly, weekly, and real-time data.

<div class="zoom_controls"> 
                              <a class="profile" id="monthly_data" href="#" data-chart="line" data-range="6m">Monthly</a>
                              <a class="profile" id="weekly_data" href="#" data-chart="line" data-range="3m">Weekly</a>
                              <a class="profile" id="real_time" href="#" data-chart="line" data-range="1m">Real Time</a>
</div>
<div class="main" id="chart" style="width:700px; height:300px;"></div>

This snippet of JavaScript is responsible for calling a PHP file to retrieve data and display it using Highcharts:

function cpu_current() {
        //current_cpu_data.php retrieves the data from a flat file
    $.getJSON('current_cpu_data.php', function(data) {
        var chart = new Highcharts.StockChart({
            chart: {
                borderColor: '#98AFC7',
                borderRadius: 20,
                borderWidth: 1,
                renderTo: 'chart',
                type: 'line',
                marginRight: 10,
                zoomType: 'x'
            },

            exporting: {
                enabled: true
            },
            
            legend: {
                enabled: true,
                backgroundColor: '#FCFFC5',
                borderColor: 'black',
                borderWidth: 2,
                width: 500,
                shadow: true
            },
            
            plotOptions: {
                series: {
                    lineWidth: 1
                }
            },
            
            rangeSelector: {
                enabled: false              
            },
            
            scrollbar: {
                enabled: false
            },
            
            navigator : {
                enabled : false
            },
            
            xAxis: {
                gridLineColor: '#EEEEEE',
                gridLineWidth: 1
            },
            
            yAxis: { 
                labels: {
                    style: {
                        color: 'blue'
                    }
                },
                gridLineColor: '#EEEEEE',
                gridLineWidth: 0,
                tickInterval: 20,
                min: 0,
                max: 100,
                plotLines: [{
                    value: 70,
                    color: '#FF3300',
                    dashStyle: 'line',
                    width: 1,
                    label: {
                        text: 'Threshold=70%',
                        align: 'right',
                        style: {
                            fontWeight: 'bold'
                        }
                    }
                }],
                title: {
                    text: '% CPU Utilization',
                    style: {
                        color: 'blue'
                    }
                }
            },
            
            credits: {
                enabled: false
            },
            
            title: {
                text: 'CPU',
                style: {
                    color: '#333000',
                    fontSize: '14px'
                }
            },
            
            subtitle: {
                text: '10 minute peaks in last 24 hours'
            },
            
            tooltip: {
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y} </b><br>',
                valueDecimals: 2
            },
            
            series: data

        });
    });
}

In order to switch between different tabs, I can use jQuery click events as shown below:

$("#monthly_data").click(function() {
    hmms_cpu_current();
});
$("#weekly_data").click(function() {
    hmms_cpu_weekly();
});
$("#real_time").click(function() {
    cpu_current();
});

My query relates to ensuring that if a user selects the "real_time" tab but does not interact with any other tabs, the data updates automatically via AJAX calls. However, if the user switches to the "monthly_data" tab, the automatic update should stop. How can this be achieved based on the provided code?

Answer №1

If you're utilizing the MVC Model, Ajax can be implemented by using the onclick method within a specific JavaScript function.

<script type="text/javascript">
  function retrieveData() {
    $.ajax({
        type: 'GET',
        async: false,
        url: 'yourcontroller/youraction',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data) {
            var obj = $.parseJSON(data);

            $.each(data, function (i, item) {

                alert(item.text); // manipulate the returned value here
            });


        },
        error: function () {
            output.text('There was an error loading the data.');
        }
    });
}

Answer №2

One approach I would suggest is incorporating a JavaScript Timer() or setTimeout() that will automatically resend the ajax call and refresh the page.

Alternatively, offering the user the choice to manually trigger this functionality by wrapping it in a Function could be beneficial.

By assigning an ID to the Timer, you can easily pause or resume its operation as needed.

Answer №3

Revise all your functions to return a jqXHR in the following manner:

function get_cpu_data() {
                //Utilize $.getJSON to obtain jqXHR, enabling ajax termination.
       return $.getJSON('current_cpu_data.php', function(data) {
              //Insert your code here
}

Implement abort within your event handlers:

var currentRequest;

    $("#monthly_data").click(function() {
            if (currentRequest){
               currentRequest.abort();//End ongoing ajax request
            }
            currentRequest = get_cpu_monthly();
        });
        $("#weekly_data").click(function() {
            if (currentRequest){
               currentRequest.abort();//End ongoing ajax request
            }
            currentRequest  = get_cpu_weekly();
        });
        $("#real_time").click(function() {
            if (currentRequest){
               currentRequest.abort();//End ongoing ajax request
            }
            currentRequest  = get_cpu_data();
        });

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

Challenges encountered when trying to access the arrays within Braintree

I'm puzzled as to why this code is behaving unexpectedly. My goal is to extract the timezone from inside an array. $transaction = $gateway->subscription()->find($_GET["id"]); echo '<pre>' , var_dump($transaction->billingPerio ...

Is it possible to utilize an await in an rxjs observable?

Implementing an interceptor for my HTTP requests requires the use of the access token from the user instance. Within my app component, I initialize the user: app.component.ts private async restoreUser(): Promise<UserModel | any> { // ... some vi ...

Searching for a button within the <InsertItemTemplate> using jQuery

I need to implement a small jQuery script that darkens the background of a page, displays a small form, and then removes the form and restores the background when the form is submitted or cancelled. Although I have successfully demonstrated this functiona ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Send properties to the makeStyles function and apply them in the CSS shorthand property of Material UI

When working with a button component, I pass props to customize its appearance: const StoreButton = ({ storeColor }) => { const borderBottom = `solid 3px ${storeColor}`; const classes = useStyles({ borderBottom }); return ( <Button varian ...

Unable to access the uploaded file on the server

Scenario : When a user uploads an image and clicks on the "save" button, I successfully save the image on the server with 777 permission granted to the folder... https://i.sstatic.net/gcIYk.png Problem : However, when I try to open the image, it does n ...

Inject props into a Component nested within a Higher-Order-Component (HOC)

In attempting to grasp the concept of creating a React Higher Order Component from this particular article, I find myself struggling to fully understand and utilize this HOC. interface PopupOnHoverPropType { hoverDisplay: string; } const WithPopupOnHov ...

Creating cartoons from images using JavaScript

Recently, I've been experimenting with comicify for a new project. I found that by right-clicking on an image online, copying it, and then pasting it into this demo page created by the author, everything works smoothly. However, I wanted to take it a ...

Converting the Javascript UUID function to C code

I'm in the process of converting a unique UUID creation formula from JavaScript to C. The challenge lies in finding a solution without relying on extensive crypto library dependencies that are typically associated with existing C libraries. JavaScrip ...

Is your React useContext() function not accessing the correct context values?

Here is the code snippet I'm having trouble with: Context.js: const Context = createContext(); export default Context; ContextProvider.js: import Context from './Context'; const ContextProvider = () => { .... return(<Context.Pr ...

Every time I attempt to send a post request, I receive back only the creation date and the unique objectID

Whenever I send a post request, only the created date and objectID are returned. Whenever I send a post request, only the created date and objectID are returned. This issue persists even after multiple attempts. I attempted to verify it using Postman ...

Unable to refresh HTML table using Vuex data in Vue JS

I am new to working with Vue.js and particularly Nuxt. I am facing an issue with updating a table using data fetched from the backend. Even though I can see the data in the Vuex tab when the page loads, I cannot seem to populate the table with it. The func ...

Guide on sending several HTTP requests from a Node.js server with a shared callback function

Is there a way to efficiently make multiple HTTP calls in a Node.js server with a shared callback function? Are there any modules or libraries that can help with this? ...

Need help accessing data from an API using Axios.post and passing an ID?

Can someone help me with passing the ID of each item using Axios.Post in order to display its data on a single page? The image below in my Postman shows how I need to send the ID along with the request. Additionally, I have the first two URL requests for t ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

Error: nextjs 13 is unable to access the 'limit' property because it is undefined

An error of type TypeError has occurred: There seems to be an issue while fetching data from the API. The value is not being retrieved properly. Cannot read properties of undefined (reading 'limit') at GET (webpack-internal:///(sc_server)/. ...

Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with: var example1; var hp = ["p"]; document.addEventListener("DOMContentLoaded", function(event) { hp = ["x"]; example1 = new Vue({ el: '#example-1', data: { iLoveMysel ...

The functionality of jQuery's nth-child selector can sometimes be unpredictable

Currently, I am working on getting this code to function properly: // Home status history handler $('div.rel-wrap table tr').on('click', function(){ // retrieves the relevid from the table var relevrow = $(this).closest(' ...

Utilize the "require" keyword to bring in multiple items instead of using the "import" statement

I'm looking to incorporate Apollo Client into my project using the following syntax. import { ApolloClient, InMemoryCache, ApolloProvider, gql } from '@apollo/client'; However, my project setup only supports the use of the "require" keyword ...

Retrieve the value of a variable by referencing the variable name as a string in JavaScript

If I have: var red = ["#F33121", "#F06562", "#90A4AE"]; //my array called red. var blue = ["#345678", "#234423", "#435223"]; //my array called blue. var color = $('.element').text(); // = red Therefore, when console.log(color); is called, it re ...