Error when sending variable from AJAX to PHP - javascript

I'm generating table rows with data from a database.
Below is my code:
<table class="table table-hover" id="dashEventTable">
<thead>
<tr>
<th>Created at</th>
<th>Seminar Name</th>
<th>Quota</th>
<th>Location</th>
<th>Option</th>
<th style="display:none"></th>
</tr>
</thead>
<tbody script="javascript">
<?php
$one = 1;
$Lihat="SELECT * FROM event where status = '$one'";
$Tampil = mysqli_query( $db, $Lihat );
while ( $hasil = mysqli_fetch_array ( $Tampil ) ) {
$id_event = ( $hasil['id_event'] );
$nama_event = ( $hasil['nama_event'] );
$lokasi = ( $hasil['lokasi'] );
$kuota = ( $hasil['kuota'] );
$created_at = ( $hasil['created_at'] );
{ ?>
<tr>
<td class="created_at"><?php echo date( 'Y-m-d h:i a', strtotime( $created_at ) ); ?></td>
<td class="event_name"><?php echo "$nama_event"; ?></td>
<td class="kuota"><?php echo "$kuota"; ?></td>
<td class="lokasi"><?php echo "$lokasi"; ?></td>
<td>
<a class="btn btn-xs btn-danger btn_delete" data-toggle="modal" href="#deleteDashEvent"><i class="fa fa-trash"></i></a>
</td>
<td class="event_id" style="display:none"><?php echo "$id_event"; ?></td>
</tr><?php }
} ?>
</tbody>
</table>
Now when I click on the button inside the rows, it does two things, the first is going to this JavaScript function:
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
alert( event_id );
}
});
});
From the alert and console log, I saw that I got the correct ID for the event id of the row. The data will then be sent to the PHP file above, and inside that PHP is this:
<?php
if ( isset( $_POST['send'] ) ) {
$id_event = $_POST['send'];
} else {
echo "The data has not been received!";
}
The second thing it does is go to this div for the delete confirmation:
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
</form>
When the DELETE button is clicked, it will then go to this PHP file:
<?php
session_start();
include( "config.php" );
if ( isset( $_POST['admin_delete_event'] ) ) {
include( "contain_data.php" );
$zero = 0;
$delete_query = "UPDATE event, jadwal_acara, waktu_pendaftaran
SET event.status = '$zero', jadwal_acara.status = '$zero', waktu_pendaftaran.status = '$zero'
WHERE event.id_event = '$id_event'
AND jadwal_acara.id_event = '$id_event'
AND waktu_pendaftaran.id_event = '$id_event'";
if ( mysqli_query( $db, $delete_query ) ) {
$delete = "Data has been deleted";
echo $delete;
} else {
echo "Error: " . $delete_query . "<br>" . mysqli_error( $db );
}
} else {
echo "The button is not detected!";
}
The problem I am having is that I received this error when I click the delete confirmation button:
The data has not been received!
Undefined variable: id_event in...
Which means that I fail in sending the data.
What am I doing wrong and how can I resolve it?
EDIT: after adding error handling to the php file, the value sent by the ajax is null instead of the id_event, do you guys know why?

Update your AJAX With:
$.ajax({
url: "contain_data.php",
method: 'post',
data : 'send='+event_id,
success:function(){
alert(event_id);
}
});
try to pass your event_id using this way
data : 'send='+event_id,
because you have taken
method: 'post',
Hope it will help

I got your error . Upto submit your first form through is correct when you go for delete conformation you miss that event_id and you just using that one in you "admin_delete_event.php" file that why it giving error
Undefined variable: id_event in...
Now just add an hidden input field in form and submit it then the event_id will be available to you.
<form action="admin_delete_event.php" enctype="multipart/form-data" id="event_delete_row" method="post" name="delete_event_row">
<div class="modal fade" id="deleteDashEvent">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button aria-label="Close" class="close" data-dismiss="modal" type="button">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Delete Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure want to delete this event?</p>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal" href="#">Batal</a>
<button class="btn btn-primary btn_confirm_delete" name="admin_delete_event" type="submit">DELETE</button>
</div>
</div>
</div>
</div>
<input type="hidden" name='event_id' value='id' id='event'>
</form>
And just change this in your 1st Ajax
$( ".btn_delete" ).click(function() {
var $row = $( this ).closest( "tr" ); // Find the row
var event_id = $row.find( ".event_id" ).text();
console.log( event_id );
$.ajax({
url: "contain_data.php",
method: 'post',
data: {
'send': event_id
},
success: function() {
$('#event').val(event_id);
alert( event_id );
}
});
});
Then it will work fine.

Related

ajax get data request url not found but already exist, Laravel 8

hello guys i have a problem with my ajax data json, i have a project about scan a barcode with a webcam but it just views the code of the barcode, the data in the database not call in my ajax, this is the code of blade, i'm using a modal
this is the modal
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="scanModalLabel">Scan Barcode</h5>
<button type="button" class="close close-btn" data-dismiss="myModal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<dl class="row">
<dt class="col-sm-4"><h4>Kode Barang</h4></dt>
<dd class="col-sm-8" id="kode_barang"></dd>
</dl> <hr>
<table class="table align-items-center tabel-detail" >
<thead class="thead-light">
<tr>
<th>Nama Barang</th>
<th>Harga Jual</th>
<th>Stok</th>
<th>Insert</th>
</tr>
</thead>
<tbody class="list">
</tbody>
</table>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
this is the jquery code
var args = {
autoBrightnessValue: 100,
resultFunction: function(res) {
[].forEach.call(scannerLaser, function(el) {
$(el).fadeOut(300, function() {
$(el).fadeIn(300);
});
});
scannedImg.attr("src", res.imgData);
scannedQR.text(res.format + ": " + res.code);
console.log(res.code);
document.getElementsByName('qrcode')[0].value = res.code;
var kode= res.code;
$('#kode_barang').text(': '+kode);
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data)
{
$('.list').html(data.table_data)
}
});
$('#myModal').modal('show');
},
this is the controller
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::findOrFail($id)
->where('kode_barang', '=', $id)
->select('produks.*')
->first();
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
this is the route
Route::get('transaksi/scan', '\App\Http\Controllers\ProdukController#cekScan')->name('daftar_produk.scan');
what should i do the error said "jquery.min.js:2 GET http://localhost:8080/rezkastore1/%7B%7B%20route('daftar_produk.scan')%20%7D%7D?kode=2135758676 404 (Not Found)"
Seems like problem with URL.
You can't access the route in JS file.
Make a global variable in blade for ajaxURL then use in JavaScript.
<script>
var ajaxURL = '{{ route('daftar_produk.scan') }}';
</script>
<script src="xyz.js"></script>
I have no idea wether you write your Javascript section, in Laravel Blade View or in separate JS file. If you write it within Laravel Blade Template, you may use
$.ajax({
url:"{{ route('daftar_produk.scan') }}",
but I recommend you to write complete URL within your AJAX call. Make your AJAX call like this :
$.ajax({
url:"/transaksi/scan",
method:'GET',
data:{kode:kode},
dataType:'json',
success:function(data) {
$('.list').html(data.table_data)
}
});
Instead of using findOrFail(), you can use find() or regular where() with error handler, because findOrFail() will returns 404 not found if it can't find any records, here is the cekScan function
public function cekScan(Request $req)
{
$id = $req->get('kode');
$output='';
$produk = Produk::where('kode_barang', '=', $id)->first();
if (!$produk) {
return json_encode(['table_data' => 'Barang Tidak Ditemukan']);
}
$no = 0;
$data = array();
foreach ($produk as $list) {
$no ++;
$output .= '<tr><td>'.$no.'</td><td>'.$list->nama_barang.'</td><td>'."Rp.".format_uang($list->harga_jual).'</td><td>'.$list->stok.'</td><td><a type="button" data-stok=(('.$list->stok.')) data-id=(('.$list->id.')) data-nama=(('.$list->nama_barang.')) data-kode=(('.$list->kode_barang.')) data-harga=(('.$list->harga_jual.')) class="btn btn-primary btn-pilih" role="button">Insert</a></td></tr>';
}
$data = array(
'table_data' => $output
);
return json_encode($data);
}
Maturnuwun

How to insert data from a modal PHP Codeigniter

I have a modal form (simple) that I want to insert in my BD, but I'm not getting the expected result
modalview
this is the button that calls my modal:
<button type='button' class='btn btn-info' data-toggle="modal" data-target="#modal-default-cliente"><span class='fa fa-plus'></span></button>
this is my modal:
<div class="modal fade" id="modal-default-cliente">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Agregar Usuario</h4>
</div>
<div class="modal-body">
<form method="POST" id="clienteform">
<div class="form-group">
<label for="nombrecompleto">Nombre Completo:</label>
<input type="text" class="form-control" name="nombremodal" id="nombremodal" required="required">
</div>
<div class="form-group">
<label for="telefono">Teléfono:</label>
<input type="text" class="form-control" name="telefonomodal" id="telefonomodal">
</div>
<div class="form-group">
<label for="direccion">Dirección:</label>
<input type="text" class="form-control" name="direccionmodal" id="direccionmodal">
</div>
<div class="form-group">
<input type="submit" name="action" class="btn btn-success" value="Guardar">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
This is my Javascript code, which by the way the parameters of the form arrive
$(document).on("submit", "#clienteform", function(event){
event.preventDefault();
var nombre = $("#nombremodal").val();
var telefono = $("#telefonomodal").val();
var direccion = $("#direccionmodal").val();
$.ajax({
url: base_url+"mantenimiento/Ventas/agregarClientemodal",
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
This is my action in the "Ventas" Controller:
public function agregarClientemodal(){
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
}
and finally my function in the Sales model:
public function agregarUsuariomodal($data){
return $this->db->insert("Clientes",$data);
}
I'm new to Codeigniter, and when I click on my save button, my modal window does nothing
Expected behavior: save the record and hide the modal
behavior obtained: clicking on the submit does nothing
what am I doing wrong? What do I need to validate? any help for me?
Hope this will help you :
Pass form post values with ajax's data using var formdata = $(this).serialize();, and use site_url() for the URL
Your ajax should be like this :
$(document).ready(function(){
$("#clienteform").on("submit", function(event){
event.preventDefault();
var formdata = $(this).serialize();
$.ajax({
url: '<?=site_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
data : formdata,
success: function(data)
{
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
});
Your agregarClientemodal method should be like this :
public function agregarClientemodal()
{
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
echo "success";
exit;
}
Your base_url variable is not defined in javascript/jquery.
So you need to change that line into:
$.ajax({
url: '<?php echo base_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
it will generate correct url.
Further you can check console for error logs.

Pass different PHP variables to modal and show in form inputs

I have a table: Users with 3 different attributes:
ID
firstname
lastname
In the index.ctp page for Users, for each data entry, I have the Edit action available to use.
<div>
<table class="usersTables" id="userTable">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('firstname') ?></th>
<th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= h($user->firstname) ?></td>
<td class="actions">
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $user->id], ['class' => 'view', 'data-id' => $user->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(function () {
$('.edit').click(function () {
ev.preventDefault();
var userId = $(this).attr('data-id');
$('#editModal').modal('show');
alert(userId);
});
});
</script>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editModalLabel">Edit</h4>
<div>
<div class="col-sm-6">
<?= $this->Form->input('firstname', ['class' => 'form-control', 'label' => 'First Name', 'placeholder' => 'First name', 'id' => 'firstname']); ?>
</div>
<div class="col-sm-6">
<?= $this->Form->input('lastname', ['class' => 'form-control', 'label' => 'Last Name', 'placeholder' => 'Last name', 'id' => 'lastname']); ?>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="savebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
Clicking the Edit button in the table first gives me an alert pop up that tells me which $user->id I selected, then opens up the Edit modal. However, my form inputs are still empty even though the related attributes for that specific datat entry are fileld in the database. I'm not sure how to connect the data-id variable that was then defined as a JavaScript variable to the form input which I believe requires a PHP variable again ($user->firstname).
If I use 'value' => $user->firstname in the firstname form input, I get the data from the very last data entry every time (eg. if I have 3 data entries in my Users table, I will always get the 3rd entry's firstname).
Glad you researched about AJAX. First you need to create a function in your controller that will return a user's details.
// Just an example in the UsersController
public function userDetails($id = null) {
$userDetails = $this->Users->find('all'['where(['id' => $id])])->first();
$this->set(array(
'output' => $userDetails,
'_serialize' => 'output',
'_jsonp'=>true
));
}
Then setup an ajax request from your view.
// in your index.ctp's script
<script type="text/javascript">
$(function () {
$('.edit').click(function () {
ev.preventDefault();
var userId = $(this).attr('data-id');
$('#editModal').modal('show');
$.ajax({
url:"localhost/your_project/Users/userDetails/"+userId+".json",
type:'POST',
success:function(res) {
console.log(res); // check the response in your console
if(res) {
$('#firstname').val(res.firstname);
$('#lastname').val(res.lastname);
}
}
});
});
});
You can send the userId as a post data for the function's parameter.

Codeigniter: Ajax sending id & name but function is receiving only id

I'm getting the id but not the name, what's wrong i'm doing ?
Please take a look at my CI code and ajax function below:
This is View on which i'm calling ajax:
<div class="modal fade" id="myModal<?php echo $values->season_id; ?>"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update Seasons</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="hiddenValue" name="hiddenValue" value="<?php echo $values->season_id; ?>">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Season Name:
</label>
<div class="title_right">
<div class="input-group">
<input type="text" class="form-control" name="update_name" id="update_name" value="<?php echo $values->names; ?>">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" id="submit" value="Save changes">
</div>
</div>
</div>
</div>
This is Ajax Function:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
alert("Ajax function started working");
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
dataType: 'json',
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
alert("changes made");
}
}
});
});
});
And here i'm trying to capture the value:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$result = $this->model_season->update_season($update_id,$update_name);
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
You use
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
but where your $query. As your code It should have as following
if ($result)
{
$data = array(
'season_id' => $result->season_id,
'names' =>$result->names
);
echo json_encode($data);
}
Now use $result->season_id instead of $query->season_id and make sure you use row() method in your model update_season() for returning desired values

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