Yii CgridView bulk delete - ajax

In many of my Models' CgridViews I have a bulk delete function: a chechboxColumn and a delete button which deletes all the checked users. For that I am using ajax in the admin and a new action in the controller.
All this works fine until I add pagination to th gridview, which is not saving the checked rows in the previous pages.
I tried to use
'enableHistory'=true,
but it did nothing (and from what I'v read I'm not the only one :mellow: ) , so I downloaded this extension: selgridview
The extension works - when I move through the pages , the checked rows stay checked BUT , my bulk delete function is seeing only the checked rows of the page I'm in right now.
this is the ajax I'm using:
<?php
Yii::app()->clientScript->registerScript('delete','
$("#butt").click(function(){
var checked=$("#person-grid").yiiGridView("getChecked","person-grid_c11");
var count=checked.length;
if(count>0 && confirm(" are you sure you want to delete "+count+" people ? "))
{
$.ajax({
data:{checked:checked},
url:"'.CHtml::normalizeUrl(array('person/remove')).'",
success:function(data){$("#person-grid").yiiGridView("update",{});},
});
}
});
');
?>
Now , maybe thats a silly question but I know little about javascript.
I'm not even sure that the problem is in the ajax . . . .
Help would be much appreciated :rolleyes:

I am using selgridview extension.
Here is my code for deleting the selected users
//delete multiple users at once
$('#delete_selected_items_button').on('click', function () {
var selected = $("#users-grid").selGridView("getAllSelection");
//if nothing's selected
if ( ! selected.length)
{
alert('Please select minimum one user to be deleted');
return false;
}
//confirmed?
if ( ! confirm('Are you sure to delete ' + selected.length + ' users?')) return false;
var multipledeleteUrl = "<?php echo Yii::app()->baseUrl;?>/users/multipledelete";
$.ajax({
type: "POST",
url: multipledeleteUrl,
data: {selectedUsers : selected},
success: (function (e){
//just to make sure we delete the last selected items
$("#users-grid").selGridView("clearAllSelection");
//we refresh the CCGridView after success deletion
$.fn.yiiGridView.update("users-grid");
}),
error: (function (e) {
alert("Can not delete selected users");
})
});
})
On UsersController, actionMultipleDelete() do something like this
if (Yii::app()->request->isAjaxRequest)
{
$selectedUsers = Yii::app()->request->getPost('selectedUsers');
//iterate through all ids
foreach ($selectedUsers as $id)
{
//delete the user here...
}
}

I don't know about this plugin and how it saves what checkboxes are
checked, but you can look into that and then send that information
to your controller.
Alternatively you can save which models should be
deleted in a session. On a checkbox click() (check if the check box is checked
or unchecked) event call your controller with ajax to save the
model's id in your session. then when the user clicks delete you can
retrieve this data from the session.

Related

Print fetched data with ajax in codeigniter

I am trying to make chat room with ajax. Till now I am able to store data in db without page load. And also able to fetch data and display onscreen using ajax. Here is what I did with ajax
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val(); //chat message from input field
var chatroomid = $("#chatroomid").val(); //hidden input field
$.ajax({
url: baseurl+'User_dash/chatmessage', //An function in ctroller which contains only insert query
type: 'post',
data: {chatmsg:chatmsg, chatroomid:chatroomid},
dataType: 'json',
success: function (argument) {
if(argument['status']){
$("#chatting").append(" <li id='"+getvalue+"'>"+argument['msg']+"</li>."); //Here I am printing chat message which resently submitted in database
}
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
This method with ajax is working fine. But issue I faced here is that, this display chat message only to current user. Not to other side of user whome message is being sent via chat.
To solve this issue I come up with one idea which doesn't seems to be working as I planed. Here it is how I modified my previous ajax code..
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val();
$.ajax({
url: baseurl+'User_dash/chat', //controller function which contains insert query, after that select query to fetch chat data from db and store in view
type: 'post',
data: {chatmsg:chatmsg},
dataType: 'json',
success: function (argument) {
if(argument['status']){
//Not doing anything here this time
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
In updated version of script I thought If I will call a controller function which is storing data in view (chat page) then It will run query and print data without page load.
But with this method, I am getting chat onscreen only after page load, although it is getting submit in db with ajax fine.
Here is controller code for my second method with ajax if needed
public function chat(){
if(!empty($_POST['chatmsg'])){
$chatdata = array('CHAT_ROOM'=>$_POST['chatroomid'],
'VENDOR'=>$this->session->userdata('USER_ID'),
'BUYER'=>49,
'MESSAGE'=>$_POST['chatmsg']
);
$this->db->insert('tbl_chat', $chatdata); //inserting data
}
$data['chatroom'] = $this->db->where('CHAT_ROOM', 1)->get('tbl_chat')->result_array(); //fetching data from db
$this->load->view('userDash/chat', $data);
}
How do I achieve to run insert and then select query and print data on screen without page load?
Where I am getting wrong?
I solved my issue earlier, What I did was, just added this jquery script which keep refreshing (every second) a certain div inside page in which I have put query to fetch chat from db and printing them.
setInterval(function(){
$("#chatting").load(location.href + " #chatting");
}, 1000);

Updating "tr" data in laravel

I'm facing difficulty in doing this task :
- I have a table that have an add delete , update buttons for every single row I've done the add and delete thing by adding data-attribute for each button according to the row's data Id. It works perfectly for deleting and inserting elements. Yet i can't find a way to update every single row so i need help !
Note: I'm updating my elements using Ajax.
Any strategy ? i can post a screenshot for my code/view cause it is a bit too long .
More explanation : when you click on the edit button $(this) and delete button hide , and check button appears . inputs are no longer hidden for this row so the user updates the data of this row then he checks it.
The data must update inside the database .
I'm stuck nowhere because every row has its own id and its own values and only one query must be run for every row ( which is the same query for all the rows ) . It's more likely having one form for the whole table that updates only the row that must be updated .
After you click on edit button
$(document).on('click', '.btn-edit-interview', function() {
var id = $(this).attr('data-interview-id');
var selector = ('' + '.tr' + id + '');
var selectordelt = ('' + '.' + id + '');
var selectorsave = ('' + '#save-'+id + '');
$(this).hide();
$(selectordelt).hide();
$(selectorsave).show();
$(selector).prop('disabled', false);
$(selector).addClass("form-control");
$(selector).css('border: 1px solid rgb(204, 204, 204);margin-top: 16px;');
});
I just need help in finding a way do make the update query for every single row .
//HTML
<tr data-unique="{!! $yourVariable->id !!}">
<td><input value="{!! $yourVariable->value !!}"></td>
<td><button data-update="{!! $yourVariable->id !!}">Update</button></td>
</tr>
//AJAX
$('button[data-update]').click(function() {
var itemID = $(this).attr('data-update');
//Will contain value of input in that tr only
var input = $('tr[data-unique="+itemID+"] input').val();
$.ajax({
url: '/update',
type: 'POST',
dataType: 'json',
data: {item: itemID, anotherValue: input},
success:function(data){
if(data['status'] == "success"){
alert("Updated");
}
}
});
return false;
});
//Controller
public function update(Request $req){
YourModel::where('id', $req->input('item'))->update(['column' => 'value']);
return response()->json(['status' => 'success']);
}
//Route
Route::post('/update', 'YourController#update');
Hope that help

Zend Form: onchange select load another view content

In my application I have a form in controller/index that consists out of 3 select boxes. When all three boxes have a value selected I need to show additional html and extra form options in the same view based on those select values. The obvious solution seems to make an ajax call to another action that handles the database operation and creates a view and loading that view into the controller/index.phtml
I have been able to load a view of another action in the index.phtml by using:
$('#select').change(function() {
event.preventDefault();
var id = $(this).attr('id');
$('#results').show();
$('#results').load('/controller/index/' + $(this).attr('value'));
return false;
});
However I need to pass the variables of all three select boxes and for that I alternatively used:
$('#select1').change(function() {
var select1 = $('#select1').val();
var select2 = $('#select2').val();
var select3 = $('#select3').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '/controller/index/',
data: { select1: select1, select2: select2, select3: select3},
success: function(result){
var return1 = result.return1;
var return2 = result.return2;
}
});
});
The last method works in as far that I do see the variables passed in the headers and the response contains the view, but I cant fix it that just the content of the ajax view is placed within the index view. (Ofcourse by not using AjaxContent switching, the ajax view will load but that includes the complete layout as well.) Anything that I echo in the ajax action or ajax view do not show in the index view. Any pointer would be more than welcome
EDIT
the ajax action now looks like
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$select1 = $this->_request->getParam('select1');
$select2 = $this->_request->getParam('select2');
$select3 = $this->_request->getParam('select3');
// DO THE OTHER STUFF AND LOGIC HERE
$results = array(
'return1' => 'value1',
'return2' => 'value2'
);
$this->_response->setBody(json_encode($results));
and the controller init
public function init() {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('ajax', 'json')->initContext();
}
So everything works, I can see the returned values in the response by using developer tool (network) in my browser, however I just do not know how I can use this to "update" the view
You can do two things:
You can enable the layout of the action you are calling via ajax. See you have disabled layout so even if the view phtml file of the ajax action contains something, it won't show. You can enable layout, use text/html dataType instead of json and show the returned HTML somewhere.
Or, in the success event of the ajax call, write javascript codes to update DOM.
Thanks #Salman for your suggestions as they lead me in the right direction and I managed to solve the problem.
I managed to pass multiple parameters with the ajax .load() call by passing them as get parameters.
The results of the ajaxAction could then be formatted in the ajax.ajax.phtml view and were consecutively
shown within the #results div that resides in the index.phtml where the select boxes are.
controller/index.phtml
<div id="results" style="display:block;">Select all three values</div>
IndexController init and ajaxAction
public function init() {
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('ajax', 'html')->initContext('html');
}
public function ajaxAction() {
$select1 = $this->_request->getQuery('select1');
$select2 = $this->_request->getQuery('select2');
$select3 = $this->_request->getQuery('select3');
$form = new Application_Form();
// Database operations and logic
$this->view->form = $form;
$this->view->array = $somearray;
}
}
jquery script in index.phtml
$(document).ready(function(){
$('.selector').change(function() {
var select1 = $('#select1').val();
var select2 = $('#select2').val();
var select3 = $('#select3').val();
if ( select1 && select2 && select3) {
$('#results').show();
$('#results').load('/controller/ajax?select1=' + select1 + '&select2=' + select2 + '&select3=' + select3);
}
});
});
controller/ajax.ajax.phtml
<?php if ( $this->array ) : ?>
<?php echo( $this->form ); ?>
<?php else: ?>
Nothing found for selected values
<?php endif ?>

Codeigniter: Click on a link then get value from checked checkboxes to pass to controller

I have three menus(ADD, EDIT, DELETE), and many items with checkboxs. I checked some checkboxs then when i click on DELETE, I want to delete all the checked items. I just don't know how can i detect which checkboxs are checked with codeigniter. Anyone have any ideas?
You can use Jquery to get the current selected items like this:
var values = $('input:checkbox:checked.class_you_like').map(function ()
{
return this.value;
}).get();
After this you can post the values to CI with ajax:
$.ajax(
{
type: 'post',
url: '/dummy/delete',
data:{ids: values}
});
Then in CI/PHP
function delete()
{
$ids = $this->input->post('ids');
// !this should be done in a model
$this->db->where_in('id_column', $ids);
$this->db->delete('your_table');
}
Put all the checkbox elements in a form then give DELETE as an submit button then in your contrller
public function delete()
{
$for_delete = $this->input->post('checkbox');//Hope that your all checkbox names are array of checkbox[];
$for_delete = implode(',',$for_delete);
$this->model_to_delete->delete($for_delete);
}
in your model delete all the records whose id's are there in the for_delete array()

CI + AJAX, Double posting + refreshing of page

So I have a normal form with 1 textarea and two hidden inputs, which I would like to post via AJAX to a CI controller I have that inserts the information into the database.
The problem I'm having is that a) the page action is still called and the output of the controller is displayed and b) because the initial AJAX request is still processed plus the extra loading of the action target the information gets inserted twice.
This is my javascript code:
$(document).ready(function() {
$("#submit-comment").click(function(){
var post_id = <?=$p->id?>;
var user_id = <?=$user->id?>;
var content = $("textarea#content").val();
if(content == '') {
alert('Not filled in content');
return false;
}
$.ajax({
type: "POST",
url: "<?=site_url('controller/comment')?>",
data: "post_id="+post_id+"&user_id="+user_id+"&content="+content,
success: function(msg){
alert(msg);
}
});
});
});
I have tried doing
...click(function(e)... ... e.preventDefault
with no luck.
What am I doing wrong? :P
Thanks
Ps. All the information is processed properly and accessed, it's just the preventing the form which is screwing it up..
Just realised I was using a input type="submit", rather than input type="button".
Doh!

Resources