What could be causing my ajax function to fail on yii2?

Hello there, I am seeking guidance on how to implement an ajax function in yii2.

I am currently developing a product within the yii2 framework and wish to incorporate charts such as chartJs, googleChart, or d3. In the index file of the backend area (xx/xx/xx/dashboard/index.php), I aim to make an ajax request to another PHP file located in the same folder (xx/xx/xx/dashboard).

However, despite successful results when testing my files (indexAjax and phpDB) outside of the framework folders, they fail to work once integrated into the framework.

Below is the snippet of code from my index file:

<canvas id="mycanvas" width="400" height="400"></canvas>
<script>
$(function()
{
$.ajax({
url: "chartData.php",
type:'POST',
data:{'trigger':'trigger'},
success: function(data) {
alert(data);
console.log(data);
var idTab = [];
var resultatTab = [];

for(var i in data) {
idTab.push("data " + data[i].id);
resultatTab.push(data[i].resultat);
}

var chartdata = {
labels: idTab,
datasets : [
{
label: 'Player Score',
backgroundColor: 'deepskyblue',
borderColor: 'dodgerblue',
hoverBackgroundColor: 'orange',
hoverBorderColor: 'yellow',
data: resultatTab
}
]
};

var ctx = $("#mycanvas");

var doughnutGraph = new Chart(ctx, {
type: 'doughnut',
data: chartdata,
options:{responsive:false}
});
},
error: function(data) {
alert(JSON.stringify(data));
console.log(data);
}
});
}); // end jQuery
</script>

This is the content of the second PHP file:

<?php
if (isset($_POST['trigger']))
{
// setting header to json
header('Content-Type: application/json');

// database connection details
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'lab');

// establish connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}

// query to retrieve data from the table
$query = sprintf("SELECT * FROM score");

// execute query
$result = $mysqli->query($query);

// iterate through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}

// free memory associated with result
$result->close();

// close connection
$mysqli->close();

// output the data
print json_encode($data);
 
}

Note: I acknowledge that I did not strictly adhere to the principles of MVC by placing everything in the same folder, but it was a conscious decision.

Thank you for your assistance.

Answer №1

To understand how routing works in yii2, it's important to explore the framework's documentation at http://www.yiiframework.com/doc-2.0/guide-structure-overview.html or take a look here: http://www.yiiframework.com/doc-2.0/guide-start-hello.html

You cannot directly call a PHP file.

For example, in Javascript:

$.get('/site/user-messages', function (data, status) {

                        if (status !== 'success') {
                                console.log('ERROR: '+ status);
                                return;
                        }
                        allData = JSON.parse(data);

});

In this code snippet, 'site' represents the controller and 'user-messages' represents the action. Specifically, the prettyUrl mode is enabled in urlManager for this scenario.

Answer №2

Insert the contents of your charData.php files into a suitable action, such as inside siteController.php

 public function actionChartData() {
    // Add your code here
    .........

    return $this->render('your_related_view', [
         /* Define your variables here */
        'my_var' => $my_var,
    ]);
}

Then call the action via ajax using:

$.ajax({
url: <?php echo   \yii\helpers\Url::to(['/site/chart-data']) ?>,
type:'POST',
data:{'trigger':'trigger'},
success: function(data) {
        // Add your success functionality here

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

Issue with FILE_APPEND and file_put_contents function not functioning as expected

My approach involves sending form data as JSON via AJAX to a PHP file, which then saves the JSON information in a text file on the server. An issue arises when using FILE_APPEND, as the data is not written to the file if the JSON content already exists wi ...

SecurityError: The dubious operation triggers CORS to persist in its insecurities

I have developed an HTTP server using Express in Node.js. This server is currently running locally on port 3000. There is a served HTML page called "index.html" which makes AJAX GET requests for contents (in HTML format). These AJAX contents are also serv ...

Showing local storage on a webpage using Jquery

I have encountered an issue where I can successfully add and remove items from local storage, but the added item does not display on my HTML page. The expected behavior is that when an item is added to local storage, it should be visible on a favorites pag ...

Leveraging Ajax in Django to communicate with the backend and showcase the outcome

I need assistance with implementing ajax functionality to send user input to a Django backend for text processing, and then display the results. However, due to my limited experience with ajax, I'm struggling to figure out where I'm going wrong. ...

Printing only the form.blade.php file using Laravel's dompdf module

I need assistance with exporting or printing only a specific form as a PDF. The form is located within an app.blade.php file and includes various components such as a side panel, header, and mid content (highlighted in the red "box"). However, I want to pr ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

What is the reason for XMLHttpRequest.status being equal to 0 in all browsers except for Internet Explorer?

I am encountering a frustrating issue... After developing a standalone RESTful.NET webservice using C#, I noticed that when I make a XMLHttpRequest to fetch JSON data, all browsers, except for IE, fail to retrieve the data. The problem lies in the status ...

Establishing a time frame using AJAX through a separate PHP script

In order to display either a video or an image based on a specific time range, I want to utilize the client's local time by taking it from the website. Here is what I have done so far: 1st file (time.php): <?php $b = time (); print date("H:i", $b ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...

The image loads successfully from an AJAX request in CodePen, but fails to load in the local

I am currently working on integrating a weather API into my basic website and I would like to incorporate the weather icons as well. The API request successfully works in both my local and live environments, however, I encounter an error with the icon spec ...

Switch from using a curl query to making an ajax query with mootools

My current approach involves using curl to fetch json data from nuxeo. Below is the function I am currently using: curl -X POST -H "Content-Type:application/json+nxrequest" -d "{ params: { query:'SELECT * FROM Document' ...

The concept of method overloading within the Yii framework model

I am interested in implementing method overloading within a Yii framework model. Similar to Java, where method overloading allows for multiple methods with the same name but different parameters, I am curious if this concept can be applied in PHP Yii fram ...

Can you explain the distinction between submitting a form through the ajax() method versus using <form action="xyz" method="POST"> to communicate with a servlet or PHP script?

Currently, I am exploring jQuery Mobile and implementing a basic form submission to a servlet using a straightforward method. However, after some research on Google, I discovered that most developers are opting for the Ajax method instead. I'm curious ...

Using PHP Propel ORM to perform a left join on a many-to-many relationship in MySQL

There are two tables I'm working with: one called "meeting" and the other called "attendance". The "attendance" table is a many-to-many relational database structured as follows: Attendance: user_id | meeting_id | invited --------+----------- ...

`I'm encountering issues when trying to pass an array through localStorage into a new array`

This is a complex and detailed question that I am struggling to find a solution for. Despite using deprecated mysql due to hosting limitations, the problem lies elsewhere. Part 1 involves dataLoader.php, which queries the database and retrieves posx and p ...

When the if-else statement is executed, it showcases two strings:

Learning Experience: Unveiling My Lack of Cleverness Update: It appears that utilizing PHP in my current setup is not possible. As a result, I'll take some time to contemplate while banging my head against a wall. Despite that, thank you all for your ...

Retrieve a targeted tag from the API snippet

I need to extract the IMG SRC tag from the given code: <pod title="Scientific name" scanner="Data" id="ScientificName:SpeciesData" position="200" error="false" numsubpods="1"> <subpod title=""> <plaintext>Canis lupus familiaris</plain ...

What are the steps for utilizing svn+ssh within a PHP script?

I am facing a challenge in accessing the repository from a CakePHP project called fredistrano (which allows CakePHP deploys with a web 2.0 interface). The issue arises when I try to access fredistrano located in my web broadcasting directory on a shared Un ...

Identify the Google Maps Marker currently displayed on the screen

Is there a way to generate a list of markers within the zoom range for Google Maps, similar to the functionality on this site I'm curious if I can achieve this using jQuery or if there is a built-in function for Google Maps v3? Thank you! ...

Attempting to load using ajax, Chrome and jquery-mobile will modify the location of the window through setting window.location.href

I'm encountering a challenge with my mobile application where I need to redirect users to the login page on a 401 ajax call. However, it seems that jQM is attempting to load this via AJAX when the request is sent. This solution works flawlessly for s ...