how to send variable from gridview yii to javascript - javascript

i need your help. my purpose is update data in modal form, but i get problem and almost one week i didn't find the solution. the problem is i don't know how to send id from gridview to javascript function and in javascript function will throught to controller but in controller I can't get the variable of id. this my code.
//code in admin.php
'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>'{view} {update} {delete} ',
'buttons'=>array(
'update' => array
(
'click'=>'js:function()
{
var idcab=($(this).parent().parent().children(":nth-child(1)").text());
editCabang(idcab);
$("#dialogClassroom").dialog("open");
}',
),
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog
'id'=>'dialogClassroom',
'options'=>array(
'title'=>'Tambah Cabang',
'autoOpen'=>false,
// set to auto open for testing only
'draggable'=>true,
'resizable'=>true,
'closeOnEscape' => true,
// 'show'=>'fade',
// 'hide'=>'fade',
'position'=>array(300,50),
'modal'=>true,
'width'=>'700px',
'height'=>'auto',
'close' => 'js:function(event, ui) { location.href = "./admin" }'
),
));?>
<div class="divForForm"></div>
<?php $this->endWidget();?>
<script type="text/javascript">
function editCabang(idcab)
{
//alert(idcab); when i alert the id show
<?php echo CHtml::ajax(array(
'url'=>array('Tbcabang/update'),
'data'=> 'js:$(this).serialize(),"idcab2":$(this).idcab', //i want send variable idcab2 to controller
'type'=>'post',
'dataType'=>'json',
'success'=>"function(data)
{
if (data.status == 'failure')
{
$('#dialogClassroom div.divForForm').html(data.div);
// Here is the trick: on submit-> once again this function!
$('#dialogClassroom div.divForForm form').submit(editCabang);
}
else
{
$('#dialogClassroom div.divForForm').html(data.div);
setTimeout(\"$('#dialogClassroom').dialog('close') \",3000);
}
} ",
))
?>;
return false;
}
//code in controller (update action)
public function actionUpdate()
{
//$id=100;
$id=$_POST[idcab2]; //the id is empty
$model=$this->loadModel($id);
if(isset($_POST['Tbcabang']))
{
$model->attributes=$_POST['Tbcabang'];
if($model->save())
{
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'success',
'div'=>"Tambah cabang berhasil"
));
exit;
}
else
// $this->redirect(array('view','id'=>$model->id));
$this->redirect(array('view','id'=>$model->id_cabang));
}
}
if (Yii::app()->request->isAjaxRequest)
{
echo CJSON::encode(array(
'status'=>'failure',
'div'=>$this->renderPartial('_form', array('model'=>$model), true,true)));
exit;
}
else
$this->render('update',array('model'=>$model,));
}

The expression js:$(this).serialize(),"idcab2":$(this).idcab doesn't make any sense..
How is $(this) going to work, and it should be just a javascript object..
To pass the idcab variable passed to the function to the controller you need to use just the idcab not $(this).idcab

There are various ways you can fix it . But what I get you want to show dialog for editing a grid so the best way is to to pass id to that dialog e. g
//code in admin.php
'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>'{view} {update} {delete} ',
'buttons'=>array(
'update' => array
(
'click'=>'js:function()
{
var idcab=($(this).parent().parent().children(":nth-child(1)").text());
//set the id
$("#dialogClassroom").dialog("option","idcab",idcab);
$("#dialogClassroom").dialog("open");
}',
),
Then add open event to dialog to fetch the data/or set the form :
'close' => 'js:function(event, ui) { location.href = "./admin" }'
'open' => 'js:function(event, ui) {
var idcab=$(ui).dialog("option","idcab");
//fetch the data for idcab and fill the dialog form , is that you want ?
//if yes call the ajax function now
}'
Probably you can set the open event function of dialog to set a hidden form field. You know what you are doing .

Related

Add element to form with Ajax call in CakePHP 4 breaks FormProtector

I'm using CakePHP 4.1.
I want to be able to dynamically add elements to an accordion interface with an Ajax call.
In the template that defines the accordion, I have this:
<?php
$k = 0;
echo '<div id="accordion-menu">';
if (isset($pageContent->config['items'])) {
foreach ($pageContent->config['items'] as $k => $item) {
echo $this->element('PageContents/form/item', [
'k' => $k,
'pageContent' => $pageContent,
]);
}
}
echo '</div>';
echo $this->Html->tag(
'button',
$this->Icon->fa('plus'),
[
'escape' => false,
'onClick' => "addItem('" . $this->Url->build(['action' => 'addItem']) . "', " . $k . ");",
'class' => 'btn',
'type' => 'button',
]
);
?>
This is my addItem JS function:
function addItem(url, k) {
$.ajax({
url: url + '/' + k,
success: function (data) {
$('#accordion-menu').append(data)
},
error: function () {
console.log('An error occured.')
}
})
}
And this is the action that that function calls:
<?php
namespace App\Controller\Content;
use App\Controller\AppController;
class ImagesController extends ContentsController
{
public function addItem($k = null)
{
$this->viewBuilder()->setLayout('ajax');
// some additional logic...
$this->render('/Element/PageContents/form/item');
}
}
In my Element/PageContents/form/item template, I have to call unlockField() because I do some JS handling of my input fields.
This is the error that I get:
FormProtector instance has not been created. Ensure you have loaded the FormProtectionComponent in your controller and called FormHelper::create() before calling FormHelper::unlockField().
In the AppController, however, I call $this->loadComponent('FormProtection'); in the initialize() method.
The Element/PageContents/form/item template is also included in the accordion template (as shown in the first snippet), and in that case the unlockField() call works without errors.
The problem only happens when I try to dynamically add an element after the page is rendered.
By debugging, I found out that in that case $this->Form->formProtector is indeed null.
What am I doing wrong here? What is the correct way to add UI elements to a form after it's been rendered, without reloading the whole page?

If condition not working in model of codeigniter

I am trying to implement a "like" button for my website. I am using Codigniter, Ajax and Jquery. When the like button is clicked data should be entered to database and if unlike button is pressed data should delete from database. But I am facing a problem in model, data is not added to database when I click like button. Please help me to find a solution.
This is my Jquery file "likeitem.js"
function likeItem(postId)
{
if ($("#likeItem_"+postId).text() == "Like")
{
$("#likeItem_"+postId).html('Unlike');
var purpose = "Like";
}
else
{
$("#likeItem_"+postId).html('Like');
var purpose = "UnLike";
}
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "purpose=" + purpose,
success : function()
{
}
});
return false;
}
This is my model "usermodel.php"
public function itemLike()
{
$id = $this->session->userdata('userID');
$postId = $this->input->post('postId');
$purpose = $this->input->post('purpose');
if($purpose=="Like")
{
// echo 'test';
// exit();
$data = array(
"userID" => $id,
"postTextID" => $postId,
);
$this->db->insert('like', $data);
}
else
{
echo 'hai';
}
}
This is my view file "home.tpl"
<li><a class="like-unlike" href="#" id="likeItem_{$item['postID']}" onclick="likeItem({$item['postID']})">Like</a></li>
This is my Controller "user.php"
public function likeItem()
{
$this->usermodel->itemLike();
}
You mistake here. You forgot to put & symbol. Try this code.
data : "postId=" + postId + "&purpose=" + purpose,
Full code:
If you want to manipulate result returned from ajax, you can do something on success block as following code :
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "&purpose=" + purpose,
success : function(data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
});

php + JS button value save

Logic is that , on click div.buttons gonna hide and get second form : save date to mysql .. problem is in this : 1) i have to save grab name or value from buttons : problem no refresh page . i tried send date to php with ajax , with GET or POST methodes from js .. buttons are taken mysql and echoed in php like this : PHP: foreach ($res as $row) {
echo '<tr><td><button id="pupShow" name="'.$row["ID"].'">'.$row["SubjectName"].'</button> </td></tr>';
} JS:
$("button#pupShow").click(function () {
$("div.pupInput").show("slow");
$("div.showMarks").toggle("slow");
$("div.lessons").toggle("slow");
alert(this.name);
// $GLOBALS['myglob'] = this.name;
// window.location.href ="subID.php?subID="+this.name;
// return false;
this is js were i handle click on button
any help ?
i got eye on transforming first buttons into selected manue . so i could grab them by name from php , but its destroy my visual ..
If you don't want to reload the page, then you can try:
foreach ($res as $row) {
echo '<tr><td><button id="pupShow" name="'.$row["ID"].'" onclick="return false;">'.$row["SubjectName"].'</button> </td></tr>';
}
or
$("button#pupShow").click(function (el) {
el.preventDefault();
var data = 'nume=' + el.val()
$.ajax({
url: "subID.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
if (html) {
// animations here
alert('Success! Form submitted');
} else{
alert('Error! Please try again');
}
}
});
I didn't test it but it should help you understand how the function will look like.
So you want to submit some data without refreshing the page? Since you're using jQuery, you can do something like this:
$.post("test.php", {name: "Mathematics"}).done(function(data) {
console.log("Response loaded: " + data);
});

Ajaxsubmitbutton Not Passing ID

I have a problem using bootstrap modal for updating data.
On CGridView selectionChanged, it will trigger a function to show modal dialog form and insert the data to the form
Here is my CGridView :
<?php
$this->widget('customCGridView', array(
'id'=>'contactperson-grid',
'itemsCssClass' => 'table table-bordered',
'selectionChanged'=>'showmodal',
'dataProvider' => $contactperson->search(),
'emptyText' => '',
'enableSorting' => false,
'htmlOptions' => array('class' => ' '),
'columns' => array('nama', 'jabatan')
));
?>
On selectionChanged, it will trigger this script to open the update dialog modal and fill the form with selected CGridView column data :
function showmodal(grid_id) {
var keyId = $.fn.yiiGridView.getSelection(grid_id);
keyId = keyId[0]; //above function returns an array with single item, so get the value of the first item
$.ajax({
url: '<?php echo $this->createUrl("suppliertable/personview"); ?>',
data: {id: keyId},
type: 'GET',
success: function(data) {
$("#contact-person-modal").html(data);
$('#kontakmodalupdate').modal('show');
}
});
}
Here is the actionPersonView which will be executed upon selecting column :
public function actionPersonView($id) {
$contactperson = SupplierContactPersonTable::model()->findByPk($id);
if ($contactperson === null)
throw new CHttpException(404, 'The requested page does not exist.');
$this->renderPartial('updateForm', array('contactperson'=> $contactperson));
Yii::app()->end();
}
Now, here is the problem :
When I Click update button on update form, I need to pass ID to my action :
public function actionPersonUpdate($id) {
$model2=$this->loadModel2($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['SupplierContactPersonTable']))
{
if($model2 === null) {
throw new CHttpException(404, 'The requested page does not exist.');
}
$model2->attributes=$_POST['SupplierContactPersonTable'];
$model2->save();
}
}
To pass this value, I'm using AjaxButton on my form:
<div id="contact-person-modal">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'suppliercontactmodalform',
'htmlOptions' => array(
'class' => 'smart-form',
'novalidate' => '1',),
'enableAjaxValidation' => false,));
?>
...
<footer>
<button type="button" class="btn btn-labeled btn-danger cancel-button" style="float: left">
Hapus Pengguna
</button>
<?php
echo CHtml::ajaxButton('Update', Yii::app()->createUrl('suppliertable/personupdate',array('id'=>$contactperson->contact_person_id)), array('type'=>'POST'), array('type'=>'submit',"class" => "btn btn-primary"));
?>
<button type="button" class="btn btn-default" data-dismiss="modal">
Batal
</button>
</footer>
...
However, it seems like ID isn't passed. Here is Firebug console :
POST http://localhost/webapp/index.php/suppliertable/personupdate/
400 Bad Request
As you can see, no ID is passed.
But, if I use static parameter value :
echo CHtml::ajaxButton('Update', Yii::app()->createUrl('suppliertable/personupdate',array('id'=>'5')), array('type'=>'POST'), array('type'=>'submit',"class" => "btn btn-primary"));
The ID is passed :
POST http://localhost/webapp/index.php/suppliertable/personupdate/5
So, I think the problem is here, is not outputing value :
$contactperson->contact_person_id
Here is generated jQuery from Yii :
jQuery('body').on('click','#yt0',function({
jQuery.ajax({
'type':'POST',
'url':'/webapp/index.php/suppliertable/personupdate id=',
'cache':false,
'data':jQuery(this).parents("form").serialize()
});
return false;
});
Thanks for your help :)
I've found my solution.
In case someone have the same problem, I need to update my actionPersonView method :
public function actionPersonView($id) {
if (Yii::app()->request->isAjaxRequest) {
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
$contactperson = SupplierContactPersonTable::model()->findByPk($id);
if ($contactperson === null)
throw new CHttpException(404, 'The requested page does not exist.');
$this->renderPartial('updateForm', array('contactperson'=> $contactperson),false,true);
Yii::app()->end();
}
}
I need to add in my actionPersonView method
$this->renderPartial('updateForm', array('contactperson'=> $contactperson),false,true);
And add
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
To prevent the script being executed multiple.

Having issue with LIVE UPDATING

I am making a LIVE UPDATE in CodeIgniter and it is almost working.
Just one little issue: When I click the button it also appears my navigation inside the "responds" box which is very strange.
And when I refresh the page it is removed and the record is there.
Here is an image to explain what I mean
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
//##### Add record when Add Record Button is click #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val() ==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('admin/dashboard/index'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response) {
$("#responds").append(response);
},
error:function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
</script>
EDIT:
HERE IS THE CONTROLER
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load libraries
$this->load->library('ion_auth');
$this->load->library('parser');
// Load models
$this->load->model('note_model');
// Load helpers
$this->load->helper('date');
// Set error delimiters
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
}
public function index()
{
// Check if user is loged in
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
else
{
// Create notes object
$notes = new Note_model();
// Order the notes by date post
$notes->order_by('date_post', 'desc')->get();
$recent_notes = array();
foreach ($notes as $note)
{
$single_note = array
(
'id' => $note->id,
'note_text' => $note->note_text,
'date_post' => $note->date_post,
);
array_push($recent_notes, $single_note);
}
// Get the user id as an object
$getinfo = $this->ion_auth->user($this->session->userdata('user_id'))->row();
// Create a new note
$createNote = new Note_model();
$createNote->note_text = $this->input->post('content_txt');
$created = date('Y-m-d H:i:s');
$createNote->date_post = $created;
// Validation rules
$rules = $this->note_model->rules;
$this->form_validation->set_rules($rules);
$data = array
(
'admin_content' => 'admin/dashboard',
'notes' => $recent_notes,
'username' => $getinfo->{'first_name'} . ' ' . $getinfo->{'last_name'},
);
if ($this->form_validation->run() == FALSE)
{
$this->parser->parse('admin/template_admin', $data);
}
else
{
$createNote->save();
redirect('admin/dashboard');
}
}
}
The problem is the action you are calling.
It seems admin/dashboard/index outputs the navigation as well as the data you want to display.
You should post to an action that ONLY displays the data you require, and nothing else

Categories