CodeIgniter button that works like href - javascript

I have this button
<a class="btn btn-sm btn-success" href="javascript:void(0)" title="info" onclick="delete_province('."'".$info->ID."'".')"><i class="glyphicon glyphicon glyphicon-question-sign"></i> Show File</a>';
that i want to change that button function with something like this
<a href = '<?php echo base_url().'Employees/updatepersonalinfo/'.$data; ?>' class = 'btn btn-info pull-right fa fa-edit'>&nbsp Update</a>
please notice here
echo base_url().'Employees/updatepersonalinfo/'.$data;
that im passing a data at the url for me to use the function $this->uri->segment()
how can i make the button work like href? and is there any other way that the templates wont load anymore just some of the div? thanks in advance
and also the .$data that i want to pass came from , a json?
heres additional codes to be clear
here is the controller with the button
public function index()
{
$data['content_view'] = 'TaxValues/taxvalues_read';
$this->templates->admin_template($data);
}
public function ajax_list()
{
$list = $this->TaxValues_Model->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $info) {
$no++;
$row = array();
$row[] = $info->RANGE_NO;
$row[] = $info->TAX;
$row[] = $info->PERCENTAGE." %";
$row[] = $info->VALUE;
$row[] = $info->FREQUENCY;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_provinces('."'".$info->TAX_ID."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Delete" onclick="delete_province('."'".$info->TAX_ID."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->TaxValues_Model->count_all(),
"recordsFiltered" => $this->TaxValues_Model->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
i wanted to pass the $info->TAX_ID so that for example, i want to access my existing update code,
controller function of update
public function updateinfo(){
$data['content'] = $this->TaxValues_Model->info();
$data['content_view'] = 'TaxValues/edit';
$this->templates->admin_template($data);
}
model function of update
public function info(){
$query = $this->db->get_where('emp_fi_p', array('ID_NUM' => $this->uri->segment(3)));
return $query->row();
}

Related

HTML & PHP: Wrong button allignment and wrong output

So I have this comment system made with PHP and JS (dialogify) and I have two problems: one is obviously the buttons' allignment and the second is the output of the dialog. At the end of each line i get a <br> even though the line ends without going actually on a new line and the row won't update after pressing ok, I have to reload the page to actually see the updated content.
EDIT: Now the buttons are alligned
<div class="row">
<div class="col-sm-12 text-right">
<form method="post" action="">
<button class="btn btn-warning btn-sm" id="<?php echo $row['id']; ?>" value="Edit" type="button" onclick="edit_row('<?php echo $row['id']; ?>');" /><i class='fa fa-pencil'></i></button>
<button class="btn btn-danger btn-sm" name="delete_reply" type="submit"><i class='fa fa-trash'></i></button>
</form>
</div>
</div>
Here is the code I use to display the comments.
$query_reply = $mysqli->prepare("SELECT * FROM replies WHERE postID=?");
$query_reply = $mysqli->bind_param("i",$postid);
$query_reply ->execute();
$row = $query_reply->fetch_assoc();
<div id="content_val<?php echo $row['id']; ?>"><?php echo nl2br($row['reply']);?><br /></div>
The code for the insertion
if (isset($_POST['edit_row'])) {
$sql = $mysqli->prepare("UPDATE replies SET reply=? WHERE id=? AND postID=?");
$id = $_POST['id'];
$content = $_POST['content'];
$postid = $_SESSION['id'];
$sql->bind_param("sii", $content, $id, $postid);
if ($sql->execute()) {
$sql = $mysqli->prepare("SELECT * FROM replies WHERE postID='$id'");
$sql->bind_param("i", $postid);
$sql->execute();
}
}
EDIT 2: I managed to make the content update in real time by changing the action after $sql->execute();
if ($sql->execute()) {
print "success";
} else {
$error_message = "Problem in editing Record";
}

undefined value from data attribute

i try to get the value from the data attribute and pass to the java script variable but it give the undefined value
$(document).on("click","#edit_cust",function(){
var customer_id=$(this).data("id");
var customer_name=$(this).data("name");
var customer_phone=$(this).data("phone");
var customer_addr=$(this).data("mail");
var customer_mail=$(this).data("phone");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='btn-group' role='group' >
<a id="edit_cust" data-target="#edit" data-toggle="modal"><button
type='button' class='btn btn-primary btn-sm' data-id="<?php echo
$customer["cus_id"]; ?>" data-name="<?php echo $customer["cus_name"]; ?>"
data-phone="<?php echo $customer["cus_phone"]; ?>" data-addr="<?php echo
$customer["cus_address"]; ?>" data-mail="<?php echo $customer["cus_mail"]; ?
>"><span class="fas fa-user-edit edit_data" aria-hidden='true'></span>
</button></a>
</div>
All those data attributes are present for the inner button so get the button within the clicked element.
$(document).on("click","#edit_cust",function(){
// cache buttton reference
var $btn = $('button', this);
// or $btn = $(this).find('button');
// get values from button
var customer_id = $(btn.data("id");
var customer_name = $btn.data("name");
var customer_phone = $btn.data("phone");
var customer_addr = $btn.data("mail");
var customer_mail = $btn.data("phone");
});

onclick load function in php

I m have 2 my code and one work and when i use code 2 not work.
Javascript is still the same.
This is javascript and work
function addto(selid)
{
var i;
var item = "";
for (i = 0; i < 1000; i++) {
item = "incart_"+i;
if(getCookie(item) == "")
{
setCookie(item,selid,24);
break;
}
}
}
This code work
<button onclick='addto("1");' data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button >
but when i use php does not respond
// If i use the action in php it goes.
<button <?php echo "onclick='addto('".$row["id"]. "');'"; ?> data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>
Use PHP only on the dynamic part:
<button onclick="addto('<?= $row['id'] ?>')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"></i></button>
You have an escaping issue, you can either echo the whole button and use proper escaping on the quotes, or just echo the dynamic part
Echo just the dynamic part (best option)
<button onclick="addto('<?php echo $row["id"]; ?>')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>
Echo the whole button
<?php echo '<button onclick="addto(\''. $row["id"] .'\')" data-toggle="tooltip" title="Add"><i class="fa fa-shopping-cart shop-card-icon"> </i></button>'; ?>

i get same id in array

I have recursive menu function from DB.
I add some jquery codes to it.
I click plus symbol then i can see all parent nodes.
I will add: add edit delete record buttons to popover later.
I created click function to fa fa-cog, but it is always show to same id on alert.
I try from 2 days but i can not display correct clicked id in the jquery script codes.
i wanna display correct id in popover <a href="<?php echo $Linkid ;?>"</a> window. Thanks.
<?php
// Select all entries from the menu table
$result=mysqli_query($baglan, "SELECT * FROM posts ORDER BY sira ASC");
// Create a multidimensional array to conatin a list of items and parents
$menu = array(
'items' => array(),
'parents' => array()
);
// Builds the array lists with data from the menu table
while ($items = mysqli_fetch_assoc($result))
{
// Creates entry into items array with current menu item id ie. $menu['items'][1]
$menu['items'][$items['id']] = $items;
// Creates entry into parents array. Parents array contains a list of all items with children
$menu['parents'][$items['kat_id']][] = $items['id'];
}
// Menu builder function, parentId 0 is the root
function buildMenu($parent, $menu)
{
$html = "";
$buton = '<a class="buton"><button class="btn btn-default btn-xs"><i class="fa fa-plus"></i></button> </a>';
if (isset($menu['parents'][$parent])){
$html .= "<ul>";
$html .= '<div class="left" id="nav">';
foreach ($menu['parents'][$parent] as $itemId){
if(!isset($menu['parents'][$itemId])){
$Linkid = $menu['items'][$itemId]['id'];
$ayarbuton = '<a class="goster" id="'.$Linkid.'" href="#" data-toggle="tooltip" title="'.$Linkid.'"><button class="btn btn-danger btn-xs"><i class="fa fa-cog"></i></button> </a>';
$html .="<div class='editRecord'";
$html .= "<li>".$ayarbuton.$menu['items'][$itemId]['isim'].$menu['items'][$itemId]['id']."</li>";
$html .="</div>";
}
if(isset($menu['parents'][$itemId])){
$Linkid = $menu['items'][$itemId]['id'];
$html .= "<div class='bs-example'><div id='myTooltips'>";
$ayarbuton = '<a class="goster" id="'.$Linkid.'" href="#" data-toggle="tooltip" title="'.$Linkid.'"><button class="btn btn-danger btn-xs"><i class="fa fa-cog"></i></button> </a>';
$html .= "<li>".$buton.$ayarbuton . $menu['items'][$itemId]['isim']." ID = " .$Linkid;
$html .= buildMenu( $itemId, $menu );
$html .= "</div></div></li>";
}
}
$html .= '</div>';
$html .= "</ul>";
}
return $html;
}
echo buildMenu(0, $menu);
global $Linkid;
?>
<script type="text/javascript">
$(document).ready(function(){
$(".goster").click(function(){
var linkID = $(".goster").attr("id");
alert(linkID);
$("#myTooltips a").tooltip({
template : '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-head"><h3><span class="glyphicon glyphicon-info-sign"></span> <?php echo $Linkid ;?></h3></div><div class="tooltip-inner"></div></div>'
});
});
});
</script>
<script>
$('#nav .buton').css({cursor: "pointer"}).on('click', function(){
var txt = $(this).html() == '<button class="btn btn-default btn-xs"><i class="fa fa-plus"></i></button> '?'<button class="btn btn-default btn-xs"><i class="fa fa-minus"></i></button> ':'<button class="btn btn-default btn-xs"><i class="fa fa-plus"></i></button> ';
$(this).html(txt);
$(this).nextAll('ul').eq(0).slideToggle('fast');
})
</script>
With ".goster" selector you are selecting all the elements having goster class but no way of determine which one was actually clicked.
In order to get the specific clicked element, you can use this in the click callback. Try change your handler to
$(".goster").click(function(e){
var linkID = this.id;
alert(linkID);
});
finaly i will do it,
thanks all.
<script type="text/javascript">
$(document).ready(function(){
$(".goster").click(function(e){
var linkID = e.currentTarget.id; // e.target is the clicked element
$(".goster").attr("href", linkID); // this will change the link URL
});
$("#myTooltips a").tooltip({
template : '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-head"><h3><span class="glyphicon glyphicon-info-sign"></span> TOOLTIP</h3></div><div class="tooltip-inner"></div></div>'
});
});
</script>

yii active form validation on modal dialog

I'm trying to validate CActiveForm on modal dialog. I use bootstrap.
The problem is modal dialog. When I read the contents of form during the load of main html page JavaScriopt validation works, but when I load the contents on click of button, validation scrips are gone.
Here is the view of calling page
<?php
/* #var $this SiteController */
$this->pageTitle=Yii::app()->name . ' - Все магазины';
$this->breadcrumbs=array(
'Shops',
);
$jsCreate = "$(\".createShop\").click(function(){
var target = $(this).attr('data-target');
var url = '?r=site/editShop';
$(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('create-shop-script',$jsCreate,CClientScript::POS_READY);
$jsEdit = "$(\".editShop\").click(function(){
var target = $(this).attr('data-target');
var url = $(this).attr('href');
$(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('edit-shop-script',$jsEdit,CClientScript::POS_READY);
$jsDelete = "$(\".deleteShop\").click(function(){
var target = $(this).attr('data-target');
var url = $(this).attr('href');
$(target).find(\".modal-dialog\").load(url);
});";
Yii::app()->getClientScript()->registerScript('delete-shop-script',$jsDelete,CClientScript::POS_READY);
?>
<h2>Все объекты</h2>
<!-- I created separate dialog for shop and warning because on open it shows the previous content while forming the new one
and I don't want to show shop elements on warning and vise versa -->
<!-- modal dialog for shop -->
<div id="shopModal" class="modal fade" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
</div>
</div>
<!-- modal warning dialog -->
<div id="warningModal" class="modal fade" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Название <span class="hidden-xs">объекта</span></th>
<th><span class="glyphicon glyphicon-ok visible-xs" data-toggle="tooltip" title="Статус активности"></span><span class="hidden-xs">Статус</span></th>
</tr>
</thead>
<?php foreach($shops as $shop) :?>
<?php $disabled = ($shop->active) ?'' :'gray'?>
<tr>
<td><span class="<?php echo $disabled; ?>"><?php echo $shop->name; ?></span></td>
<td>
<?php echo ($shop->active) ?"<span data-toggle='tooltip' title='Активен' class='glyphicon glyphicon-eye-open'></span>" :"<span data-toggle='tooltip' title='Неактивен' class='glyphicon glyphicon-eye-close'></span>" ?>
<a data-toggle='modal' data-target='#shopModal' class="editShop" href="?r=site/editShop&id=<?php echo $shop->id; ?>"><span data-toggle='tooltip' title='Редактировать объект' class="glyphicon glyphicon-edit"></span></a>
<a data-toggle='modal' data-target='#warningModal' class="deleteShop" href="?r=site/deleteShop&id=<?php echo $shop->id; ?>"><span data-toggle='tooltip' title='Удалить объект' class="glyphicon glyphicon-remove-circle"></span></a>
</td>
</tr>
<?php endforeach; ?>
</table>
<button style='float:right;' data-toggle='modal' data-target='#shopModal' class="createShop btn btn-primary"><span data-toggle="tooltip" title="Добавить объект"><span class="glyphicon glyphicon-plus"></span> <span class="hidden-xs">Добавить объект</span></span></button>
This is the view of form, that appears inside modal dialog
<?php
/*
#var $this SiteController
#var $form CActiveForm */
?>
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'shop-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
'htmlOptions'=> array('class'=>'bottom0',),
'action'=>"$url&id={$model->id}",
));?>
<div class="modal-content panel-primary">
<div class="modal-header panel-heading">
<button type="button" class="close panel-title" data-dismiss="modal" aria-hidden="true"><span data-container="body" data-toggle="tooltip" title="Закрыть">×</span></button>
<h4 class="modal-title panel-title"><?php echo $title;?></h4>
</div> <!-- end modal-header -->
<div class="modal-body">
<div class="form-group">
<?php echo $form->textField($model,'name',array('data-toggle'=>'tooltip', 'title'=>'Название', 'class'=>'form-control', 'placeholder'=>'Название', 'maxlength'=>'50')); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="form-group">
<label data-toggle="tooltip" title="Статус активноси">
<?php echo $form->checkBox($model,'active') .' '. $form->label($model,'active') . $form->error($model,'active'); ?>
</label>
</div>
</div> <!-- end modal-body -->
<div class="modal-footer">
<!-- Save button -->
<button type="submit" class="btn btn-primary"><span data-toggle="tooltip" title="Сохранить"><span class="glyphicon glyphicon-ok"></span> <span class="hidden-xs">Сохранить</span></span></button>
<!-- Cancel button -->
<button type="button" class="btn btn-default" data-dismiss="modal"><span data-toggle="tooltip" title="Отменить"><span class="glyphicon glyphicon-remove"></span> <span class="hidden-xs">Отменить</span></span></button>
</div> <!-- end modal-footer -->
</div>
<?php $this->endWidget(); ?>
This is my Shops model
<?php
/**
* This is the model class for table "shops".
*
* The followings are the available columns in table 'shops':
* #property integer $id
* #property string $name
* #property string $active
*/
class Shops extends CActiveRecord
{
public function tableName()
{
return 'shops';
}
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name', 'length', 'max'=>255),
array('active', 'length', 'max'=>1),
array('id, name, active', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array();
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'name' => 'Name',
'active' => 'Active',
);
}
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
This is my site controller that deals with shop create/update/delete
public function actionEditShop($id=null)
{
if (!$this->checkAuthenticated()) return;
if(isset($_POST['ajax']) && $_POST['ajax']==='shop-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
$model = $this->loadShop($id);
if(isset($_POST['Shops']))
{
// create/update shop
$fields = $_POST['Shops'];
$fields['id'] = $id;
$model->attributes=$fields;
if($model->save())
$this->redirect(array('shops'));
} else {
// open form to create/update
$this->renderPartial('classifier',array('model'=>$model, 'title'=>'Объект', 'url'=>'?r=site/editShop'), false, true);
}
}
public function actionDeleteShop($id, $confirmed=null)
{
if (!$this->checkAuthenticated()) return;
$model = $this->loadShop($id);
if (isset($confirmed)){
$model->delete();
$this->redirect(array('shops'));
} else {
$this->renderPartial('warning',array('url'=>"?r=site/deleteShop&id=$id&confirmed=1",));
}
}
private function loadShop($id=null)
{
if ($id){
$model=Shops::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,"Объект под номером $id не существует.");
} else {
$model = new Shops; // creates with active='1'
$model->active = '1';
}
return $model;
}
You need to explicitly tell your controller to include your scripts using the processOutput parameter of renderPartial(). When set, processOutput() is called which:
Postprocesses the output generated by render(). This method is invoked
at the end of render() and renderText(). If there are registered
client scripts, this method will insert them into the output at
appropriate places. If there are dynamic contents, they will also be
inserted. This method may also save the persistent page states in
hidden fields of stateful forms in the page.
You should also uncomment
$this->performAjaxValidation($model);
and look at Yii renderpartial (proccessoutput = true) Avoid Duplicate js request if you use processOutput.

Categories