Unable to send post parameters to Yii2 controller using an XHR request

Within the context of my project, I am making an xhr request to a yii2 controller.

Here is how the request is structured in my view:

var xhr = new XMLHttpRequest();

xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/json");                
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

xhr.onreadystatechange = function () {
     if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
           console.log(xhr.responseText);
     }
};

// Output on console first
console.log({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken}); 


xhr.send({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken}});

And here is my controller:

public function actionTargetController() {

    if(Yii::$app->request->isAjax) {

        Yii::$app->response->format = Response::FORMAT_JSON;

        if (Yii::$app->request->isPost) {

            $post = Yii::$app->request->post();
            return $post; // Print out $post 
        }
   }
}

However, when I attempt to send the data using xhr.send(), I do not receive any response in the yii2 controller and the result is always '[]' (empty array).

I have also attempted to send the data using the FormData Object with the same outcome.

Where could I be going wrong? Thank you in advance for your assistance.

PS:

The _csrf parameter is not being passed either, so I have disabled csrf validation in the beforeAction method.

Answer №1

Adjusting the mime type and modifying the data being sent.

var xhr = new XMLHttpRequest();

xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // <------ different mime type               
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

xhr.onreadystatechange = function () {
     if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
           console.log(xhr.responseText);
     }
};

var params = $('#grid').yiiGridView('getSelectedRows')
    .map(function (value) { return "selectedRowIds[]=" + value; }).join("&");

xhr.send("_csrf=" + csrfToken + (params ? "&" + params : ""));

You can retrieve the posted data in the action using:

$post = Yii::$app->request->post('selectedRowIds');

This will give you an array of integers.

If you are already using jQuery, you can simplify this process:

var params = {selectedRowIds: $('#grid').yiiGridView('getSelectedRows'), _csrf : csrfToken};
$.post('$urlToController', params).done(function(data) {
    console.log(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

What are the available methods for incorporating node.js dependencies into a Python package?

At the moment, I am working with a few Python packages that are not yet published and are used locally. For development purposes, I install these packages on Linux using a Bash script into an activated virtual environment. Here's how I do it: cd /roo ...

Issue with accessing Factory in Controller Method in AngularJS

When I invoke a factory method within the controller, everything works smoothly. However, when I call a factory method within a specific controller method, it returns as undefined. Below is my factory setup: app.factory('config', ['$http&a ...

Sticky positioning with varying column widths

How can I create HTML and CSS columns that stick together without manually specifying the "left:" parameter every time? The current example in the fiddle achieves what I want, but requires manual setting of the "left:" value. Is there a way to make this m ...

Angularjs is struggling to connect data to the user interface

It seems that the array is not binding properly in the UI. In the HTML code, I am using dataTables. The variable $scope.successMessage is also not binding to the UI. I have tried multiple approaches but none seem to be working. Here is a snippet of th ...

Searching with Sequelize for an indirect relationship: How can it be done?

Within my database, there exists a relationship between Users and Roles. A User can have multiple Roles assigned to them. These Roles are connected to Activities in such a way that they can be associated with many different activities. This association all ...

What could be causing html-webpack-inline-source-plugin to prevent the page from refreshing after editing CSS files?

Currently, I am utilizing a plugin that embeds all CSS within the final HTML file. This method prevents the application from refreshing in development mode. Whenever I make edits to the CSS, the build process completes normally, but the styles do not updat ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

The Discord.js Avatar command does not support mentioning users

Everything seems to be working fine when I check my own avatar, but it doesn't work properly when I mention another user. Here's the code I'm using: client.on('message', message => { if (message.content === `${prefix}ava`) { ...

Which is more efficient in JavaScript: Arrays, Object literals, or JSON for achieving better performance?

I'm facing a tough decision in choosing the most effective option. Currently, I have a simple array set up like this: var array = [ '/index1.html', '/index2.html', '/index3.html' ]; While this array consists ...

Executing asynchronous promises within an asynchronous promise using the .join() method

I am currently utilizing node/express, MySQL, and Bluebird for my project. When handling client requests, I am performing async database operations. After the initial database operation callback, I need to carry out some calculations before executing two ...

Tips on incorporating asynchronous functionality in AngularJS

I am currently utilizing AngularJS version 1.5.8 and have a specific requirement. When the user clicks on the Next button, the text inside the button should change to 'Processing...' before completing the operation. I have implemented the $q serv ...

Default behavior in Fullcalendar 6 allows for rendering links on both days of the month and weekdays

Is there a way to customize the rendering of days and weekdays in Fullcalendar React? Currently, they are displayed as links by default (<a>{dayContent}</a>), but I'm looking to have them rendered as <div> or <span>. Any sugges ...

What is the most effective way to integrate a Link/URL button into the remirror toolbar?

I have chosen to utilize remirror for constructing a WSYWIG editor. The specific requirement is to include a "Link" icon in the toolbar, allowing users to select text and easily add a hyperlink by clicking on it. Although I came across the LinkExtension ...

Bidirectional data binding in Vue.js enables seamless communication between parent and child components, allowing for dynamic

Trying to implement v-for and v-model for two-way data binding in input forms. Looking to generate child components dynamically, but the parent's data object is not updating as expected. Here's how my template is structured: <div class="cont ...

Unable to update content within the `style` attribute when the HTML is stored in a variable

I am attempting to make changes to the style html - specifically by replacing a string, but unfortunately it is not functioning as expected. I am struggling to obtain the final updated html. Below is my attempt: var html = "<style>043BF83A8FB24A418 ...

Experimenting with d3 using Node.js, JSDOM, and Jasmine

I am new to Javascript and node.js, and I want to test if a basic bar chart is being rendered in my node.js/d3 application using jasmine. Could someone provide guidance on what steps I need to take? test.js (file that needs testing): var d3 = require(&ap ...

The code to assign a value to "parentId1" using window.opener.document.getElementById is malfunctioning

Trying to retrieve the value from my child.jsp and pass it to my parent.jsp using window.opener.document.getElementById("parentId1").value = myvalue; Despite no errors appearing in the console, the value is not successfully transferring to the parent pag ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

What are the best scenarios for implementing anonymous JavaScript functions?

I am currently exploring the reasons behind using anonymous JavaScript functions. Can you list out the distinctions between these functions? Describe scenarios where each function would be appropriate to use. var test1 = function(){ $("<div />" ...

Enhancing audio control features using HTML and JavaScript

After utilizing various suggestions, I have successfully created a basic audio slider that starts playing sound (at zero volume) when clicked by the user. They can then adjust the volume as needed. My only challenge is that the volume adjustment only occu ...