Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example:

{
"totalCount":"4",
"data":[
    {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...},
    {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","eventC":"23",...},
    ...and more.
]
}

The goal is to create a line chart with date vs event. Dates on the x-axis and eventA, eventB, and so forth on the Y-axis. Currently, this is what I have attempted:

var fieldsForChart = ['eventA','eventB',...]; //Currently hardcoded
Ext.define("TestBug.view.TrendsChart", {
extend: "Ext.chart.Chart",
alias: "widget.trendschart",
store: "Trends",
style: 'background:#fff',
animate: true,
shadow: true,
theme: 'Category1',
legend: {position: 'right'},
axes: [
    {
        type: "numeric",
        position: "left",
        fields: [fieldsForChart],
        title:"Start Open",
    }, 
    {
        type: "Time",
        dateFormat:"d-M-y",
        position: "bottom",
        fields: "asOfDate",
         title: 'Date'
    }
],
 series: [
    {
        type: "line",
        axis: "left",
        xField: "asOfDate",
        yField: "fieldsForChart  "
    }
 ]
});

Despite these efforts, the graph has not been successfully plotted. The aim is to dynamically render axes and series based on the JSON response. Any assistance would be greatly appreciated. Thank you in advance. :)

This is my model:

Ext.define("TestBug.model.Trend", {
extend: "Ext.data.Model",
fields: [

    {name:"asOfDate",type:"date",dateFormat:"d-M-y"},
    {name:"eventA",type:"int"},
    {name:"eventB",type:"int"},
    ...and more.
]
});

Currently, all aspects related to events are hardcoded but there is a need to generate them dynamically.

Answer №1

It may be a bit delayed, but I finally have the solution to your question after going through it thoroughly.

This particular function has worked well for me when sending parameters:
chart: object chart-line
objective: serves as reference to call data from backend (optional)
xField: represents the data needed for rendering in the category axis

prepareChartLine: function(chart, objective, xField) {
    // Defining the model and store structure is crucial to prevent errors during rendering       
    Ext.define('crm.model.' + objective, {
        extend: 'Ext.data.Model',
        fields: []
    });
    
    // Configuring the store per requirements 
    var store = Ext.create('Ext.data.Store',{
        extend      : 'Ext.data.Store',
        model       : 'crm.model.' + objective,
        proxy: {
            type: 'ajax',
            url: './php/Request.php',
            reader: {
                type: 'json',
                root: 'data'
            }
        },
        autoLoad: false
    });

    // Initiating AJAX request for data retrieval
    Ext.Ajax.request({
        url:'./php/Request.php',
        params:{
            instruction:'read',
            objective:objective
        },
        success: function(response){
            var data = Ext.decode(response.responseText);
            store.model.setFields(data.fields);

            // Setting up array series
            var series = [];
            
            // Clearing existing series
            chart.series.clear();
            
            for(var field in data.fields){
                if(data.fields[field] !== xField){
                   chart.series.add({
                       type:'line',
                       xField:xField,
                       yField:data.fields[field]
                   });

                   series.push(data.fields[field]);
                }
            }

            var mAxes = chart.axes.items;
            
            for(var axis in mAxes){
                if(mAxes[axis].type === "Numeric"){
                    mAxes[axis].fields = series;
                    mAxes[axis].maximum = data.maximum;
                    mAxes[axis].minimum = data.minimum;
                }
            }
            
            chart.axes.items = [];
            chart.axes.items = mAxes;
           
           chart.bindStore(store);
           chart.redraw();
           chart.refresh();

           store.loadRawData(data.data, false);
        },
        failure: function(response){
            Ext.Msg.alert('GascardPay',response);
        }
    });

}

We also need to configure the response JSON as follows:

{
    fields: [
        "Another",
        "Another2",
        "Another N",
        "date"
    ],
    data: [
        {
            Another: 12,
            Another2: 2,
            Another N: 30,
            date: "2015-01-03"
        },
        {
            Another: 17,
            Another2: 8,
            Another N: 0,
            date: "2015-01-04"
        },
        {
            Another: 32,
            Another2: 21,
            Another N: 3,
            date: "2015-01-05"
        },
        {
            Another: 25,
            Another2: 27,
            Another N: 15,
            date: "2015-01-06"
        },
        {
            Another: 21,
            Another2: 6,
            Another N: 40,
            date: "2015-01-07"
        }
    ],
    minimum: 0,
    maximum: 40
}

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

What causes jQuery's .width() method to switch from returning the CSS-set percentage to the pixel width after a window resize?

After exhaustively console logging my code, I have finally identified the issue: I am attempting to determine the pixel width of some nested divs, and everywhere I look suggests that jQuery's .width() method should solve the problem. The complication ...

Implement a FOR loop in conjunction with an AJAX request

My goal is to send an AJAX request with multiple form fields and use an array for validations. I would like to also pass these values via AJAX: Although I haven't used a for loop in JavaScript before, it looks familiar. The current approach of the l ...

Plugin for managing responses other than 200, 301, or 302 in forms

Currently, I am using the jQuery Form Plugin in my project. Everything works smoothly when the server sends a 200 response as it triggers the success listener seamlessly. However, according to the standard protocol, the browser automatically handles 301 ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

A unique approach to handling ngdisabled for fields that are required only

Starting off with a requirement to disable the submit button when a required field is left empty. <form name="form"> <input type="text" placeholder="First Name" data-ng-model="model.firstName" name="FirstName" ng-required="true" /><br/> ...

Ways to stop click propagation in the case of a parent anchor link containing a button among its children

Every time I click on the Link parent, it triggers a click event on the button as well. I want these events to be independent. <Link className="product-item__link" to={`/products/${product.category}/${product.id}`} > <div className ...

Is there a more secure alternative to using the risky eval() function? Do I need to take the lengthier route by implementing a switch case instead?

I've been practicing and honing my Javascript skills by working on a calculator code that initially had lots of repetitive lines. I managed to simplify it, but I am aware that using the eval() method is not generally recommended. let current = 0; f ...

Data tables pulling Json data from a PostgreSQL database are displaying null values

I have been using datatables in combination with a Postgresql server to retrieve data. To achieve this, I am utilizing the script available at http://datatables.net/development/server-side/php_postgres Although the script successfully creates a json file, ...

Guide on transferring value from a <select> element using JavaScript

I'm attempting to pass the selected value of a <select> in the onChange function. I've explored this question on SO, but unfortunately, using this and this.value hasn't been successful. I understand that the question is quite old... se ...

What is the best way to transmit the server response information from a fetch API to the client?

After receiving a response with the expected results from an API call using fetch API and a json object, I am looking for ways to send these results to the client in order to display them on the interface. The server-side operation was conducted through th ...

Adjust google maps to fill the entire vertical space available

I found this helpful resource for integrating Google Maps into my Ionic app. Everything is working smoothly, but I am trying to make the map fill the remaining height below the header. Currently, I can only set a fixed height in pixels like this: .angula ...

I encountered a problem with the Javascript toggle menu collapsing feature

I have built a custom toggle menu using Javascript: $(document).ready(function() { $('.toggle').click(function () { if ($(this).hasClass("expanded")) { $(this).next().slideUp("fast"); } else { $(&apos ...

Streamline retrieval of alphanumeric indexing within json

When accessing json data using jquery, I came across an index structure like this: data.rows[0].student_1 data.rows[0].student_2 data.rows[0].student_3 and so on... Now, I'm looking to automate this process by creating a loop that allows me to acces ...

Replace the indexOf() method to be called on a null value

I have discovered a way to override functions in JavaScript, such as indexOf(), like this: var indexOf = String.prototype.indexOf; String.prototype.indexOf = function(){ //MY CUSTOM CODE HERE return indexOf.call(this, arguments); }; By doing this ...

How to store and retrieve images using the Google Drive API in a Node.js application

I am new to working with Node.js. I have been exploring how to route an incoming image from the Google Drive API without having to download it first, as that process takes too long. My goal is to send the image directly to the client once I receive it. I ...

Issue with Datepicker validation in Angular 5 and Angular Material

I have implemented the most recent version of Angular and Angular Material. I am facing an issue with a datepicker where the validation requirements are not being met as expected. The documentation states that the required attribute should work by default, ...

Is there a way for me to determine the dimensions of the webcam display?

How do I determine the width and height of the camera in order to utilize it on a canvas while preserving proportions? I am attempting to ascertain the dimensions of the camera so that I can use them on a canvas. On this canvas, I plan to display live vid ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

What are the methods to alter validation for a Formfield based on the input from other Formfields?

My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...