The request cannot be loaded by AJAX

Currently, I am facing an issue with date filters on a line chart using Chart JS. After making some modifications, including updating the values of the date ranges, the chart seems to be malfunctioning. Strangely, there are no errors being logged in the console.

The setup involves the use of 3 PHP files: one for handling and managing a connection with SAP, another for managing the ajax call, and finally, the homepage containing the problematic chart.

The structure is as follows:

Here is the script snippet inside index.php responsible for the faulty AJAX call:

 $(document).ready(function(){
        $('#selector-ceco').on('change', function(){

            // -------------variables actualizacion graficas -----------
            //console.log($('#fecha_i').val(), typeof $('#fecha_i').val());
            var ceco = String($('#selector-ceco').val());
            var fecha_i = $('#fecha_i').val().replace(/-/g, '');
            var fecha_f = $('#fecha_f').val().replace(/-/g, '');
            //if (ceco==0) {ceco="";};
            console.log(typeof fecha_f, fecha_f);

            var montos = []; var fechas = []; var gasto_total = 0; var dates =[];
            
            $.ajax({
                url: "inc/cargar_hist_cecos.php",
                type: 'POST',
                data: {'ceco_electo':ceco, 'fecha_i': fecha_i, 'fecha_f': fecha_f},
                dataType: 'json',
                success: function(retorno, status){
                    console.log("llegue");
                    for (let i = 0 ; i<retorno.length ; i++){
                        montos.push(parseFloat(retorno[i]['TOTAL']));
                        fechas.push(retorno[i]['FECHA'].replace(/(\d\d\d\d)(\d\d)/,'$1-$2'));
                        //dates.push(Date(retorno[i]['FECHA']));
                        gasto_total += parseFloat(retorno[i]['TOTAL']);
                    };
                    
                    //console.log(typeof dates[0], Date(fechas[0]));
                    

                    gasto_ceco.data.datasets[0].data = montos;
                    gasto_ceco.data.labels = fechas;
                    gasto_ceco.update();
                }
            });

Next is the code snippet for the AJAX call handler:

<?php
include_once 'db.inc.php';

session_start();

if(isset($_POST['ceco_electo'])){
    $CONN_data = new DbS;
    
    $valores = $CONN_data->gasto_ceco( $_POST['ceco_electo'] , $_SESSION['grupo'], $_POST['fecha_i'], $_POST['fecha_f']);

    $hist = json_encode($valores);
    echo $hist;
}else{
    echo "error";
};  

?>

And here's the snippet from the connection file:

public function gasto_ceco ($CECO, $tipo, $fecha_i, $fecha_f){
            $pdo = $this->connect_sap();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $sql = <<<SQL
                    SELECT T2."OcrCode" as "CECO", sum(T2."Quantity"*T2."Price") as "TOTAL", YEAR(T4."DocDate")*100+MONTH(T4."DocDate") as FECHA
                    FROM PCH1 T2 INNER JOIN OPCH T4 on T4."DocEntry"=T2."DocEntry"
                    WHERE T2."AcctCode" like '55%' AND T4."DocDate" > '20220101' AND T4."CANCELED" <> 'N ' AND T2."OcrCode" = {$CECO} AND T4."DocDate" > cast({$fecha_i} as VARCHAR) AND T4."DocDate" < CAST({$fecha_f} as VARCHAR)
                    GROUP BY T2."OcrCode", YEAR(T4."DocDate")*100+MONTH(T4."DocDate")
                    ORDER BY YEAR(T4."DocDate")*100+MONTH(T4."DocDate") ASC 
            SQL;
            
            
            echo $sql;
            $stmt = $pdo->prepare($sql);
            
            $res = $stmt->execute();
            
            echo $res;
            
            try {
                return $gasto_ceco = $stmt->fetchAll(PDO::FETCH_ASSOC); 
            }catch(PDOException $e){
                echo "error: ".$e->getMessage();
            };
        }
    };

I have attempted creating a separate file that calls the functions and the query successfully executes. Despite trying to capture any AJAX error messages, I haven't made much progress.

Prior to this problem, I had a similar function without fecha_i and fecha_f, along with corresponding modifications, which worked perfectly fine.

**EDIT**: In case it provides some insight, here is the HTML related to the chart:

<div class="card-body">
                    <div class="chart-area">
                        <input type="date" id="fecha_i" value="2022-01-01" name="fecha_i">
                        <input type="date" id="fecha_f" value="2023-12-31" name="fecha_f">
                        <canvas id="grafico-gasto-ceco"></canvas>
                        
                        <script>
                            var labels= []; var data_gasto_raw = [];
                            var ctx_gasto_ceco = document.getElementById("grafico-gasto-ceco").getContext('2d');
                            var config = {
                                ...
                            };
                            var gasto_ceco = new Chart(ctx_gasto_ceco, config);
                        </script>
                    </div>
                </div>

Answer №1

When troubleshooting problems, it is essential to gather all relevant information about the error at hand. For client-side issues on a web page, checking the Console tab in your Dev Tools can help identify any JavaScript errors that may have occurred. Additionally, examining the Network tab can reveal if requests are being sent properly. This includes analyzing headers sent to the server, request types used, parameters passed, and the server's response. In cases of internal server errors, verifying the request's validity and form is crucial before consulting server error logs for further debugging of server-side functionalities.

In a specific scenario, it was discovered that although the request was well-formed and processed correctly by the server, an unexpected response was received on the client side. This unexpected output included an SQL query due to an echo statement within the code.

By narrowing down the scope of the problem as outlined earlier, the root cause of the issue was pinpointed. The lesson learned here is to systematically analyze the problem space, ensuring well-formed requests, proper server handling, and aligning server responses with client-side expectations when troubleshooting future problems.

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

`Is there a recommended approach for conducting a Multi-Factor Authentication test with Cypress?`

I am currently testing an application that sends out a one-time password (OTP) if the user has multi-factor authentication (MFA) enabled. I need to create an end-to-end (E2E) test for this specific functionality. Does anyone know of a tool that can help me ...

Why does my POST request result in [object Object] being returned?

I am just starting to learn AngularJS and I am unsure if my POST request is functioning correctly. After making the request, I am receiving an [object Object] response. What does this error indicate? Could it be related to an issue with the form? //Acti ...

Encountered an error trying to access an array element by index stored in a variable within Vue.JS,

It appears that I have encountered a bug in my code. My intention is to retrieve components objects by index (for the tag), but I am facing an unusual issue. Details of the problem can be seen below: Successful scenario: let steps = ['Handler' ...

How can you include a multi-layered array within another multi-layered array using TypeScript?

If we want to extend a two-dimensional array without creating a new one, the following approach can be taken: let array:number[][] = [ [5, 6], ]; We also have two other two-dimensional arrays named a1 and a2: let a1:number[][] = [[1, 2], [3, 4]]; let ...

problem with parsing JSON

Here is a JSON string example: {"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01} I ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...

Tips for utilizing an iOS application to transfer an image to a Node.JS server

Hello everyone, I'm facing a challenge where I am attempting to upload an image from my iOS device to a web server that is written in Node.JS. On the web server, I am using formidable and it functions properly when I upload a file via a browser. Howe ...

Oops, looks like the server is experiencing some technical difficulties. The request is taking too long to process and has timed out

I find myself in a predicament with my shared hosting. Despite modifying my ajax requests to be smaller and adding timeouts after each request, the issue persists. How can I resolve this problem while using shared hosting? Note: set_time_limit(0); is not p ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Potential PHP/Javascript Concurrency Issue

As a newcomer to the world of web programming, I am still learning about Javascript, PHP, Ajax, and more. Despite my efforts to find a simple solution to a particular issue through Google searches, I have hit a roadblock. It seems like there might be a rac ...

Display an image in response to a button click using JavaScript

I am currently working on a feature that will display information when a radio button is pressed. I also want to include an image, but I am facing an issue where the text displays correctly but the image does not appear. What steps should I take to resolve ...

Saving components locally (vue2)

Looking for help with passing data from Props to Data in vue.js? Check out this Stack Overflow discussion. If you're running into issues, take a look at this sandbox example: https://codesandbox.io/s/u3mr8. Concerned about side effects of copying ob ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

Tips for building a Text Box component in React

I'm diving into a fresh Web App React project and looking to make it user-friendly by adding a Text Box. However, I'm unsure of the process needed to accomplish this task within the given react code. import React, { Component } from 'react& ...

What is causing this infinite loop in JavaScript?

I dread this task. It's the final small piece of a huge project, and my brain is completely fried... Here's the code snippet. It's supposed to check if an element is overflowing and resize the font accordingly. However, it seems like the lo ...

Issue with Reactjs not triggering the onChange callback in the child component

I created a reusable input component specifically for URLs. If a URL does not start with 'http', this component automatically adds it to the beginning. Here is the code for the component: import React, {useContext, useCallback} from 'react& ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

Including code that is tailored specifically for the Internet Explorer browser on Windows Phone devices

While testing the Google Maps API on different browsers and devices, I encountered issues with Windows Phone. It turns out that Google Maps is not supported on Windows Phones, resulting in errors. How can I set it up so that instead of displaying the map ...

Passing data from a child component to a parent component in Angular 6 using MatDialog and EventEmitter

Currently able to establish communication between two components but unsure of how to pass the user-selected value as an Object via event emitter from the MatDialog component to the parent component. I aim to transmit the selected option's value and t ...

Setting the current date of a jQuery datepicker to the value of an input tag

I am looking to assign a value to an input tag that has a datepicker attached to it. Upon initialization of the datepicker, I want to set this value. Below is a hypothetical example of what I am trying to achieve: HTML: <input id="test" value="">&l ...