Reload is done with location.reload() fallback, since you don't have jQuery or Yii PJAX JS API available.
Suggestions to get vanilla JS working like jQuery version
1. Use the same route URL
Note your original URL is:
php
Url::toRoute(['session-user/multiple-delete'])
but your vanilla JS code uses:
php
User
i dont get it.. the jquery code works fine and the vanilla js does not
Assistant
Understood — your original jQuery multi-delete works, but the vanilla JS version does not. This is very common when translating from jQuery to vanilla JS because jQuery often handles many small details automatically, e.g.,:
CSRF token injection (Yii jQuery integration injects it automatically)
Usual AJAX header setups
Yii GridView helper methods like .yiiGridView('getSelectedRows')
Proper PJAX reload calls
Why does your jQuery version work?
$('#w0').yiiGridView('getSelectedRows')
This is a Yii2-provided jQuery plugin method that detects all checked checkboxes and properly handles selection, regardless of markup.
$.ajax via Yii Jquery includes CSRF token header automatically for POST requests.
Calling $.pjax.reload({container: '#w0-pjax'}) properly triggers the PJAX container reload, refreshing grid content only — no full page reload.
Why vanilla version likely fails
1. Selection of checked rows is manual and could be faulted
Your vanilla JS gets checkboxes by:
js
var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked');
This assumes:
The checkboxes live inside container with ID w0
Their name attribute is exactly selection[]
Confirm in browser devtools that these assumptions hold.
2. CSRF token missing or not sent correctly
jQuery AJAX uses Yii's yii.getCsrfToken() or automatic header injection, your vanilla JS has to:
Ensure <meta name="csrf-token" content="..."> tag really exists in HTML head before your vanilla JS runs.
Otherwise server blocks POST requests because CSRF validation fails.
3. Request format and server side parsing
You send POST with:
User
Assistant
Thanks for confirming your page does have the CSRF meta tags, so that's not the issue.
What to check next, step-by-step:
1. Inspect your network request in browser devtools:
Open DevTools → Network tab
Click your vanilla JS multi-delete button after selecting some rows.
Look at the POST request to session-user/multiple-delete
Check the Request Headers:
Does it include the correct X-CSRF-Token header with the CSRF token value exactly matching the meta tag?
Check Request Payload/Form Data
Are the selected IDs sent as repeated keys like:
code
row_id=1
row_id=2
row_id=3
Check Response
HTTP status 200?
Response body JSON {success:true,...}?
If any of these don't match, then your request is malformed.
2. Confirm your POST body parameter encoding
Your vanilla JS body is:
js
body: new URLSearchParams({row_id: rowIds})
Problem is, when rowIds is an array, passing {row_id: rowIds} to URLSearchParams will not encode it as repeated keys. Instead it encodes it as a string, e.g.:
code
row_id=1,2,3
PHP will then see "1,2,3" as a string, not an array of IDs.
Fix: append each id separately, e.g.:
js
var params = new URLSearchParams();
rowIds.forEach(id => params.append('row_id', id));
Then send:
js
body: params.toString()
This ensures AJAX sends:
code
row_id=1&row_id=2&row_id=3
Which PHP interprets correctly as an array.
3. Confirm your controller’s is an array of IDs
User
code
document.addEventListener('DOMContentLoaded', function() {
var btn = document.querySelector('.js-batch-delete');
if (!btn) return;
btn.addEventListener('click', function(e) {
e.preventDefault();
var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked');
var rowIds = Array.from(checkboxes).map(chk => chk.value);
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
var url = '<?= Url::toRoute(['session-user/multiple-delete']) ?>';
var params = new URLSearchParams();
rowIds.forEach(function(id) {
params.append('row_id', id); // append each ID as its own param
});
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
},
body: params.toString(),
credentials: 'same-origin'
})
.then(function(response) {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(function(data) {
if (data.success) {
location.reload(); // or pjax reload if you have that setup
} else {
alert(data.message || 'An error occurred while attempting to delete the items.');
}
})
.catch(function() {
alert('An error occurred while attempting to delete the items. Please try again.');
});
});
});
seems to work, but im getting a double popup asking me if im sure twice
Assistant
The double confirmation popup happens because you have two separate confirmation prompts firing:
One defined in your JavaScript code:
This is your explicit call to confirm() inside your event listener:
js
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
Another triggered automatically by the data-confirm attribute on your HTML link tag used in the GridView's ActionColumn for the multi-delete button.
Why does the second happen?
In your PHP GridView widget's ActionColumn definition:
php
'buttons' => [
'multi-delete' => function ($url, $model, $key) use ($layout)
{
return ($layout->isAdmin) ? Html::a('<i class="bi bi-eraser-fill"></i>', '#', [
'title' => \Yii::t('app', 'Delete Selected'),
'aria-label' => 'Delete Selected',
'data-confirm' => 'Are you sure you want to delete this item?', // <-- Here
'data-method' => 'post',
'data-toggle' => 'tooltip',
'data-pjax' => '1',
'class' => 'js-batch-delete',
]) : '';
},
],
The 'data-confirm' => '...' attribute is processed by Yii's default JavaScript handler to automatically show a browser confirm dialog before the link is followed or AJAX request starts — which triggers your first popup.
Now, your custom JavaScript event handler also shows a confirmation prompt explicitly, so when you click the button, two confirmation dialogs appear one after the other.
How to fix the double popup confirmation
Option 1: Remove data-confirm attribute from the ActionColumn link, and only keep the JS confirmation:
Change your PHP code to:
php
User
guess ill stick with jquery since yii2 is written for it
Assistant
That’s a totally reasonable choice! Yii2’s core client-side integration is tightly coupled with jQuery, so using jQuery ensures:
Built-in helpers like yiiGridView('getSelectedRows') work out of the box.
Automatic CSRF token handling.
PJAX reload calls are straightforward ($.pjax.reload()).
Yii’s default handlers for data-confirm, data-method, and so on work without extra wiring.
If you prefer consistency and less hassle, sticking with jQuery for Yii2 projects is often simpler and more maintainable.
A quick reminder if you continue with jQuery:
js
jQuery(function ($) {
$('.js-batch-delete').click(function(e) {
e.preventDefault();
var rowIds = $('#w0').yiiGridView('getSelectedRows');
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
$.ajax({
type: 'POST',
url: '<?= Url::toRoute(['session-user/multiple-delete']) ?>',
data: {row_id: rowIds},
success: function() {
$.pjax.reload({container: '#w0-pjax'});
},
error: function() {
alert('An error occurred while attempting to delete the items. Please try again.');
}
});
});
});
If, in the future, you want to move away from jQuery (e.g. in Yii3 or standalone apps), you can revisit vanilla JS or modern frameworks with better support.
But for Yii2, jQuery remains the path of least resistance and less friction.
If you want help optimizing or cleaning up the jQuery version or combining it nicely with PJAX and your UI, feel free to ask!
e.preventDefault();
var rowIds = $('#w0').yiiGridView('getSelectedRows');
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
$.ajax({
type: 'POST',
url: '" . Url::toRoute(['session-user/multiple-delete']) . "',
data: {row_id: rowIds},
success: function() {
$.pjax.reload({container: '#w0-pjax'}); // Reload the grid via PJAX
},
error: function() {
alert('An error occurred while attempting to delete the items. Please try again.');
}
});
});
});
";
rewrite this to work with <<<js js;
Assistant
Certainly! Here's your jQuery code rewritten using PHP's HEREDOC syntax with <<<js for cleaner readability and easier maintenance:
php
$jsBlock = <<<js
jQuery(function (\$) {
$('.js-batch-delete').click(function(e) {
e.preventDefault();
var rowIds = $('#w0').yiiGridView('getSelectedRows');
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
$.ajax({
type: 'POST',
url: '{$url}',
data: {row_id: rowIds},
success: function() {
$.pjax.reload({container: '#w0-pjax'}); // Reload the grid via PJAX
},
error: function() {
alert('An error occurred while attempting to delete the items. Please try again.');
}
});
});
});
js;
If you want this link to actually trigger a PJAX request, data-pjax="1" means it will invoke PJAX replace.
But since you prevent link default behavior and handle via JS fetch, the data-pjax attribute is unneeded and can be removed to avoid interference.
Change class or selector for deeper targeting
Currently you target .js-batch-delete.
If you have multiple such buttons or complex DOM, use an ID or container-scoped event delegation.
Since there is only one button, should be ok.
Make sure PHP uses fully qualified classes (imports)
For example, in the controller:
use yii\web\Response; is needed for Response::FORMAT_JSON.
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
Action method returning JSON but your JS expects response.text()
Your JS fetch processes response as text:
js
return response.text();
But your controller returns JSON.
It's better to either responses as JSON and then parse JSON on JS side:
js
return response.json();
and then check for success property to confirm deletion.
Update your JS to:
js
.then(function(response) {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(function(data) {
if (data.success) {
location.reload();
} else {
alert(data.message || 'An error occurred while attempting to delete the items.');
}
})
Add error logging in PHP
In your catch block, log errors to investigate issues:
Since row_id is an array, URLSearchParams will encode as:
code
row_id=1&row_id=2&row_id=3
which your server should read properly.
Alternatively, you can do:
js
const params = new URLSearchParams();
rowIds.forEach(id => params.append('row_id[]', id));
and in PHP read it as row_id array.
But your existing approach usually works.
Check that $request->post('row_id') in controller is receiving all the IDs.
5. Change from response.text() to response.json()
Your original jQuery handled JSON response automatically.
Your fetch version should do:
js
.then(response => {
if (!response.ok) throw new Error('Network response not ok');
return response.json();
})
.then(data => {
if (data.success) {
location.reload(); // or PJAX reload container if possible
} else {
alert(data.message || 'Error deleting items');
}
})
.catch(() => alert('An error occurred while attempting to delete the items. Please try again.'));
Final recommended vanilla JS example code
js
document.addEventListener('DOMContentLoaded', function() {
var batchDeleteBtn = document.querySelector('.js-batch-delete');
if (!batchDeleteBtn) return;
batchDeleteBtn.addEventListener('click', function(e) {
e.preventDefault();
var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked');
var rowIds = Array.from(checkboxes).map(chk => chk.value);
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) return;
var url = "<?= Url::toRoute(['session-user/multiple-delete']) ?>";
var params = new URLSearchParams();
rowIds.forEach(id => params.append('row_id', id));
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]')||{}).content || ''
},
body: params.toString(),
credentials: 'same-origin'
})
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => {
if (data.success) {
location.reload();
} else {
alert(data.message || 'An error occurred while attempting to delete the items.');
}
})
.catch(() => {
alert('An error occurred while attempting to delete the items. Please try again.');
});
});
});
Key points:
Make sure route URL matches your controller action.
Confirm your CSRF meta tag exists.
Use consistent POST body and header setup.
Change response parsing to response.json().
Use location.reload() or implement PJAX reload if you have a PJAX library.
Use vanilla DOM API to get selected rows.
If you integrate this carefully, your multi-delete should work like original jQuery version but without jQuery dependency.
Let me know if you want me to help you implement PJAX reload without jQuery!
js
body: new URLSearchParams({row_id: rowIds})
If rowIds is an array, the conversion might not be correct.
Example: {row_id: ['1', '2', '3']} sent through new URLSearchParams() will stringify as:
code
row_id=1,2,3
(Depends on environment.)
jQuery serializes arrays as repeated params:
code
row_id=1&row_id=2&row_id=3
which PHP interprets as array.
To fix, append each value separately:
js
var params = new URLSearchParams();
rowIds.forEach(function(id) { params.append('row_id', id); });
Then set body: params.toString()
4. PJAX reload vs full reload
In jQuery code, $.pjax.reload({container:'#w0-pjax'}) works smoothly.
Your vanilla JS tries (but fails) to do the same, instead using location.reload(), forcing full page refresh.
Lack of PJAX integration means partial refreshing is not done.
5. Handling the Response Correctly
Your jQuery AJAX automatically parses JSON.
Your vanilla JS used .then(response => response.text()) — so you never had data structure to check success & messages.
Should use .then(response => response.json()) and handle.
Debug checklist
Check network request firing
Use browser dev tools — Network tab
Does the POST to /session-user/multiple-delete happen?
Are the POST parameters including all selected IDs?
Check response
Is it HTTP 200?
What is the response body? JSON with success true/false?
Check server logs for errors
Check console for JS errors
Check CSRF
Minimal working vanilla JS example based on your original jQuery:
js
document.addEventListener('DOMContentLoaded', function() {
var btn = document.querySelector('.js-batch-delete');
if (!btn) return;
btn.addEventListener('click', function(e) {
e.preventDefault();
var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked');
var rowIds = Array.from(checkboxes).map(chk => chk.value);
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
var url = '<?= Url::toRoute(['session-user/multiple-delete']) ?>';
var params = new URLSearchParams();
rowIds.forEach(function(id) {
params.append('row_id', id);
});
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
},
body: params.toString(),
credentials: 'same-origin'
})
.then(function(response) {
if (!response.ok) throw new Error('Network response not ok');
return response.json();
})
.then(function(data) {
if (data.success) {
// Try to reload PJAX container if you have PJAX JS API,
// otherwise fallback to full reload:
location.reload();
} else {
alert(data.message || 'Error deleting items.');
}
})
.catch(function() {
alert('An error occurred while attempting to delete the items. Please try again.');
});
});
});
Summary
Your jQuery version works mainly because Yii's JS libraries do a lot of the legwork:
Selection retrieval
CSRF token automatic headers
PJAX reload API
Your vanilla JS must manually handle these things.
Make sure meta CSRF tag is present.
Use correct form-urlencoded encoding with multiple values (row_id=1&row_id=2...).
Use fetch with headers and parse JSON response.
Implement PJAX reload (or use location.reload).
Verify correct URL and parameters.
Once you do this, it will work exactly like jQuery version but without jQuery dependency.
If you want, I can also help you convert the whole thing into a minimal reproducible example fully working with vanilla JS. Just ask!
$request->post('row_id')
Dump or log Yii::info(print_r($request->post('row_id', []), true));
Make sure it is an array of IDs, not a string or empty.
4. Use consistent POST URL
Your working jQuery code targets:
php
Url::toRoute(['session-user/multiple-delete'])
Make sure your vanilla JS uses the same URL, including controller and route segment names.
5. Example revised Vanilla JS snippet
js
document.addEventListener('DOMContentLoaded', function() {
var btn = document.querySelector('.js-batch-delete');
if (!btn) return;
btn.addEventListener('click', function(e) {
e.preventDefault();
var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked');
var rowIds = Array.from(checkboxes).map(chk => chk.value);
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (!confirm('Are you sure you want to delete the selected items?')) {
return;
}
var url = '<?= Url::toRoute(['session-user/multiple-delete']) ?>';
var params = new URLSearchParams();
rowIds.forEach(function(id) {
params.append('row_id', id); // append each ID as its own param
});
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') || {}).content || ''
},
body: params.toString(),
credentials: 'same-origin'
})
.then(function(response) {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(function(data) {
if (data.success) {
location.reload(); // or pjax reload if you have that setup
} else {
alert(data.message || 'An error occurred while attempting to delete the items.');
}
})
.catch(function() {
alert('An error occurred while attempting to delete the items. Please try again.');
});
});
});
6. Why jQuery works but vanilla didn't:
jQuery $.ajax serializes array correctly by default (row_id=1&row_id=2&row_id=3)
URLSearchParams({row_id: [...] })does NOT serialize arrays by repeated keys — it creates one key with a comma-separated string (or [object Object]).
So server gets wrong data — no IDs — no deletes happen.
Bottom line: Your vanilla JS multi-delete did not work because the POST data sent via fetch did not correctly encode the array of IDs.
If you fix that (append each ID individually to URLSearchParams), your vanilla JS should work fine.
If you want me to confirm or help with a full working snippet / solution, just ask!
This lets your vanilla JS handle the confirmation exactly once.
Option 2: Remove your JS confirmation and handle confirmation with data-confirm only
If you want to rely on the built-in Yii JS confirmation system, then:
Keep the 'data-confirm' => ... attribute on the link.
Remove the manual confirm() call from your JS click handler.
For example:
js
btn.addEventListener('click', function(e) {
e.preventDefault();
var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked');
var rowIds = Array.from(checkboxes).map(chk => chk.value);
if (rowIds.length === 0) {
alert('Please select at least one item to delete.');
return;
}
// Remove this confirm call, rely on data-confirm attribute instead
// if (!confirm('Are you sure you want to delete the selected items?')) {
// return;
// }
// Proceed with fetch etc.
});
But in your case this probably won’t work properly, because your JS cancels default link behavior (e.preventDefault()) and does a fetch instead — the default Yii confirmation won't work automatically in that flow.
So Option 1 is recommended.
Summary
To fix the double confirm dialog:
Remove 'data-confirm' => '...' from the multi-delete link/button tag in PHP.
Keep the confirm() call in your vanilla JS (or vice versa, but your current approach works better with manual JS confirmation).
This will display your confirmation prompt exactly once.
If you remove 'data-confirm' but keep other data- attributes needed, your multi-delete UI will be cleaner, and your manual JS confirmation will work perfectly.
If you want, I can help update the PHP snippet accordingly.