How to use Yii2 to trigger a controller action from a view and effectively debug the

Within a data grid view, there is a text input field where I intend to trigger a controller function when the field is updated. To achieve this, I have embedded a script in my form and set up a controller function.

$this->registerJs(
    "$('#product_qty').on('click', function() { 
        alert('Button clicked!'); 
        $.ajax({
            url: '".Yii::$app->request->baseUrl . '/suppliers_orders/changequantity' . "',
            type: 'post',
            data: {
                 id: '5' , 
                 _csrf : '" . Yii::$app->request->getCsrfToken() . "'
             },
            success: function (data) {
                console.log(data.search);
                },
            });
    });",
    \yii\web\View::POS_READY,
    'my-button-handler'
);

An alert message will be displayed saying 'Button clicked' when the button is clicked. However, nothing further occurs.

The Suppliers_orderController function for handling the quantity change is as follows:

public function actionChangequantity(){

        if (Yii::$app->request->isAjax) {
            $data = Yii::$app->request->post();
            $id = $data['id'];
        }
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'search' => $id,
        ];
}

In addition, I am attempting to trace the activity using PhpStorm and Xdebug, but the debugging process does not halt at the initial breakpoint within the controller. Could there be something missing or an issue with my JS function?

Answer №1

Primarily, when working with Yii2, you can utilize \yii\helpers\Url::base(); to retrieve the baseurl instead of relying on

Yii::$app->request->baseUrl;
. This is crucial in order to avoid incorrect URL output in the console due to the absence of the baseUrl. Therefore, update your code snippet as follows:

url: '".Yii::$app->request->baseUrl . '/suppliers_orders/changequantity' . "',

to the following

url: '".\yii\helpers\Url::base(). '/suppliers_orders/changequantity' . "',

Additionally, if you are using a localhost path rather than virtual hosts for both the frontend and backend, and need to access a specific controller/action, you should include index.php along with the path after web in the URL like so:

http://localhost/myproject/backend/web/index.php/suppliers_orders/changequantity

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

Testing with Jest after establishing a connection with MongoDB: A step-by-step guide

I am currently in the process of setting up testing for various routes within my Express server that rely on connectivity to my MongoDB database. I am facing a challenge in structuring the Jest file to enable seamless testing. In my regular index.js file, ...

What is the best way to retrieve a value from an `<input type="number">` element and incorporate it into the script section?

Check out this code snippet <html> <head> head <title>title</title> </head> <script> var val1 = parseInt(document.getElementById('input1')); function bytton() { window.alert(val1); ...

Getting a ThreeJS element, specifically a mesh, by its ID

I am working with a Mesh object in Three.JS. Is there a way to retrieve the Mesh object by its id and adjust its position, similar to using $(#"sample") in jQuery? Alternatively, do you have any suggestions for changing the position of objects in the ...

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

The behavior of Datatables varies depending on the screen resolution

In my data table, there are numerous entries with child tables on each row of the main table. I am currently in the process of incorporating this type of functionality into my table, with a few modifications to create a table within the child row. You can ...

Establish a connection between the MySql database in WHM (phpmyadmin) and a node.js application

Our team has been working on setting up the database connection with Mysql using node.js in Cpanel. Although I didn't create the database myself, I have all the necessary information such as the host, user, password, name of the database, and port nu ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Issue with javascript code not functioning post axios request

When working on my project, I utilize axios for handling Ajax requests. I crafted a script that attaches a listener to all links and then leverages Axios to make the Ajax request. Following the Ajax request, I aim to execute some post-processing steps. Aft ...

VueJS Component has trouble refreshing the DOM content following an AJAX Promise

I've encountered issues updating data in my Vue application after an AJAX callback. I have previously resolved similar problems by using Vue.set, but for some reason, it's not working for me today. The only difference is that I am calling a serv ...

The byte order of integer literals in JavaScript

When writing the following line in Javascript: var n = 0x1234, is it always true that n == 4660? This question could also be phrased as follows: Does 0x1234 represent a series of bytes with 0x12 as the first byte and 0x34 as the last byte? Or does 0x1234 r ...

Receive the outcome once the form is submitted

Can someone provide quick assistance? I am looking to allow users to upload a CSV file for me to parse and analyze. Once the processing is done, I need to display the results back to the users. While uploading the file, I also need to ensure that the file ...

Model for handling Node/Express requests

I always saw Node.js/Express.js route handlers as akin to client-side EventListeners such as onClick, onHover, and so on. For example: document .getElementById('btn') .addEventListener('click', function() { setTimeout(functi ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

Having trouble obtaining the correct parameter with Ajax POST request in .Net Core MVC Controller

My ViewModel structure is as follows: namespace HealthBox_WebCore_V1.ViewModel { public class ProductViewModel { public MST_ProductViewModel MST { get; set; } public List<int> FoodsID { get; set; } } } Bel ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

Remaking the functionality of jQuery's $.ajax() method while utilizing the .done() method

As a junior javascript developer, I am working on creating my own "basic" javascript framework inspired by jQuery. I am particularly fond of method chaining instead of callbacks, but I am finding it challenging to implement this. Currently, I have develop ...

Although req.user is undefined, the login process is functioning properly

Solution Quest This inquiry has been posed countless times, yet none of the responses have resolved my issue. In all my app's routes, the req.user call consistently returns undefined, regardless of which route I access. Interestingly, my login funct ...

When using Vue.js, the v-bind:class directive can be applied when an array is present and contains a specific

In my current project with Laravel and Vue.js, I am dealing with the task of creating multiple users. To accomplish this, I am constructing an array of users and populating all the necessary fields in order to store them in a database table. Once all field ...

modifying a model across multiple interfaces

My goal is to make modifications to a model in multiple views. Due to the complexity of my models with numerous properties, I need to edit them across different views. For example: The first page edits 2 properties, the second page edits 3 other propertie ...

Utilizing the JSON File in Your HTML Webpage: A Comprehensive Guide

I'm currently trying to integrate the following JSON file into my HTML page. <html> <head> <title> testing get</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> ...