Yii1: CGridView link ajax request shows 400 Bad Request - ajax

I am working on Yii 1 application. In my application, there is a CGridView where there is a link, which also fires an ajax request on onclick event. I am sending id as parameter. But the ajax return 400 Bad Request error. Please help me in this matter.
Here is the Gridview:
<h3>Civil Cases</h3>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'notifications-grid',
'dataProvider'=>$dataProvider_civil,
'summaryText' => false,
'columns'=>array(
array(
'name' => 'case_id',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->case_id),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
array(
'name' => 'caseno',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->caseno),array("civilcases/view","id"=>$data->case_id), array("onclick"=>"js:readNotification($data->id)"))'
),
'date_filing',
'next_date',
'panel_lawyer_id',
),
));
?>
here is the script:
<script>
var readNotification = function(id) {
console.log("button clicked with ID: "+id); //getting id here
$.ajax({
type:'POST',
url:'<?php echo Yii::app()->createUrl("notifications/readNotification");?>',
data: {id: id}
});
};
</script>
here is the controller:
public function actionReadNotification(){
echo $_POST['id'];
}
added readNotification function to the accessRules. When clicking on the link new page is loading but ajax request shows error.

Related

Ajax is not working in yii

In my Yii web application, any type of Ajax call like Ajax validation, Ajax for dependent dropdown etc.... Is not working.
My codes are,
In my form page:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'workdetails-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
in controller:
public function actionCreate() {
$model = new Workdetails;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Workdetails'])) {
$model->attributes = $_POST['Workdetails'];
if ($model->validate()) {
if ($model->save()) {
$this->redirect(array('create'));
}
}
}
$this->render('create', array(
'model' => $model,
));
}
For dependant dropdown:
<div class="form-group col-sm-6">
<?php echo $form->label($model, 'designationid', array('class' => 'req')); ?>
<?php
$designation = CHtml::listData(Designation::model()->findAll(), 'designationid', 'designation_name');
echo $form->dropDownList($model, 'designationid', $designation, array(
'class' => 'form-control',
'prompt' => 'Please Select',
'ajax' => array(
'type' => 'POST',
'url' => $this->createUrl('workdetails/Fetchemployee'), // here for a specific item, there should be different URL
'update' => '#' . CHtml::activeId($model, 'employeeid'), // here for a specific item, there should be different update
'data'=>array('designationid'=>'js:this.value'),
)));
?>
<?php echo $form->error($model, 'designationid', array('class' => 'school_val_error')); ?>
</div>
How to solve this...
Please help me..
Arya I had the same problem with Yii1 and i gave up using yii-ajax validation cause i could not find a way to fix it. First make sure you have initialize/ register Yii-js file these are
yiiactiveform and yii.js
If you don't have these files on your project, it means you have not registered them. To register the core JS file proceed with this config in your main.
'clientScript' => array(
'scriptMap' => array(
'jquery.js' => true,
'jquery.min.js' => true,
),
),
or if that doesn't work use this on your main view in the header section.
Yii::app()->clientScript->registerCoreScript('jquery');
You can also add it to your base controller which is at components/Controller.php
public function init() {
parent::init();
Yii::app()->clientScript->registerCoreScript('jquery');
}
On your view have this when creating your forms. It will help in placing the error messages. to your elements
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'patient-registration-form',
'enableClientValidation' => True,
'enableAjaxValidation' => FALSE,
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
for(var i in data) $("#"+i).parent().addClass("has-error");
return false;
}
else {
form.children().removeClass("has-error");
return true;
}
}',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError) {
if(hasError) $("#"+attribute.id).parent().addClass("has-error");
else $("#"+attribute.id).parent().removeClass("has-error");
$("#"+attribute.id).parent().addClass("has-success");
}'
),
'htmlOptions' => array(
'class' => 'form-horizontal form-bordered form-row-stripped',
),
));
?>
alternatively use Yii2 it has fixed alot of stufff and if you are loading the current page with ajax you need to render the the whole page including the js file again. since when you use renderPartial it doesn't initalize the js files hence no js scripts will work, including validation.

How to display info of selected items?

I am new in Yii framework, so I don't have much idea in it.
My question is, I want to get details of the company which is selected in a search box.
Code in my frontend/companies.php
<?= Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ?>
Here's my select2 widget code:-
$typeahead = Select2::widget([
'id' => 'front_companies_select',
'name' => 'state_10',
'data' => $companyNameList,
'options' => [
'placeholder' => 'Select ...',
'sigle' => true
],
]);
My js code:-
$("#getinfo").click(function(){
var obj = $("#front_companies_select option:selected").val();
console.log(obj);
});
If you want to get only company name you can try this.
$("#getinfo").click(function(){
var company_id = $("#front_companies_select option:selected").val();
console.log(company_id);
var companyName = $("#front_companies_select option:selected").text();
console.log(companyName); //here you can get company name
});
Or If you want to get whole company details then you have to call ajax like this.
$("#getinfo").click(function(){
var company_id = $("#front_companies_select option:selected").val();
$.ajax({
type: "POST",
url:"YOUR_URL/YOUR_FUNCTION_TO_GET_COMPANY_DETAILS",
data: {company_id:company_id},
dataType:'json',
async: false,
success: function (data)
{
console.log(data); //here you can get all the company details in object
}
});
});

CMultifileUpload using Ajax

The problem is that I can't get the CMultifileUpload instance in my controller/action, when I call this action using ajax
here is my code
in my view
<?php $form=$this->beginWidget('CActiveForm', array('id' => 'form',
'enableAjaxValidation' => false, 'htmlOptions' => array('enctype' => 'multipart/form-data'),)); ?>
<div class="row">
<?php
$this -> widget('CMultiFileUpload', array('name' => 'wupload', 'accept' => 'zip', \
'duplicate' => 'Duplicate file!', // useful, i think
'denied' => 'Invalid file type', // useful, i think
'max' => 1
));
echo CHtml::button('upload', array('onclick'=>'send()',));
?>
</div>
<?php $this->endWidget(); ?>
here is my action in my controller
public function actionUpload(){
$file = CUploadedFile::getInstancesByName('wupload');
var_dump($file);
}
here is my script function
function send() {
var data = $("#form").serialize();
$.ajax({
type : 'POST',
url : 'upload',
data : data,
success : function(data) {
alert(data);
},
error : function(data) {// if error occured
alert("Error occured.please try again " + data);
},
dataType : 'html'
});
}
now all what I receive after the alert shows is this
array(0){
}
I can't see my selected files, unlike if I used normal submit button, every thing worked correctly, I need someone tell me what am I doing wrong here?
You need to use the FormData object (NOTE: For IE it will only work in IE10+).
Lots of examples here, There's a jQuery one at the bottom.
https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects?redirectlocale=en-US&redirectslug=Web%2FAPI%2FFormData%2FUsing_FormData_Objects

CgridView ajax pagination in popup window

in my project i am populating a cgridview data to a popup in my base window. but when i tried doing ajax pagination it gets fails. i have made a view named list invoices having the cgrid data only.
view/user/listInvoices.php
<div id="invoice_container" name="invoice_container">
<div align="right"><img src="<?php echo Yii::app()->request->baseUrl; ?>/media/images/add_button.png" name="add_invoice" id="add_invoice"></div>
<?php
echo "INVOICES LISTING";
// Add Invoice
//echo $schedules;
?>
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $invoice->search($studioId),
'columns' => array(
array(
'name' => 'Invoice Number',
'type' => 'raw',
'value' => '$data->invoice_no',
),
array(
'name' => 'Student',
'type' => 'raw',
'value' => '$data->user_id',
),
array(
'name' => 'Invoice Date',
'type' => 'raw',
'value' => '$data->invoice_date',
),
array(
'name' => 'Invoice Amount',
'type' => 'raw',
'value' => '$data->invoice_amount',
),
array(
'name' => 'Status',
'type' => 'raw',
'value' => '$data->invoice_status',
),
),
));
?>
</div>
in my controller
on the baseview.php i send a request to the user controller to load invoice. an the ajax return success with the data a populate the grid onto the invoice controller grid.
view/user/baseview.php
$.ajax({
url:loadinvoice,
success: function(data) { $('#invoice_controller).html(data);}
});
usercontroller.php
public function actionLoadinvoice() {
$this->renderPartial('listinvoices');
}
but in my div the grid gets populated by the ajax pagination is not working. when i click the next page the browser gets reloaded. whats is the issue behind this. i think i need to bind the ajax pagination property in .bind() or .live(). but how can i do that.
Hi if you want to update the grid view with ajax you should use $.fn.yiiGridView.update(id,options) function in javascript.
Id is the id of your gridview and options are just regular ajax options.See below for full signature
/**
* Performs an AJAX-based update of the grid view contents.
* #param string the ID of the grid view container
* #param map the AJAX request options (see jQuery.ajax API manual). By default,
* the URL to be requested is the one that generates the current content of the grid view.
*/
$.fn.yiiGridView.update = function(id, options) {
var settings = $.fn.yiiGridView.settings[id];
$('#'+id).addClass(settings.loadingClass);
options = $.extend({
type: 'GET',
url: $.fn.yiiGridView.getUrl(id),
success: function(data,status) {
$.each(settings.ajaxUpdate, function() {
$('#'+this).html($(data).find('#'+this));
});
if(settings.afterAjaxUpdate != undefined)
settings.afterAjaxUpdate(id, data);
$('#'+id).removeClass(settings.loadingClass);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#'+id).removeClass(settings.loadingClass);
alert(XMLHttpRequest.responseText);
}
}, options || {});
if(options.data!=undefined && options.type=='GET') {
options.url = $.param.querystring(options.url, options.data);
options.data = {};
}
options.url = $.param.querystring(options.url, settings.ajaxVar+'='+id)
if(settings.beforeAjaxUpdate != undefined)
settings.beforeAjaxUpdate(id);
$.ajax(options);
};

Drupal 7 + JS code through the AJAX

I had created several modules extending the UI elements of the FormAPI. This works fine when I render forms in a normal way (not AJAX). But if the rendered form is delivered though the AJAX request, JS script simply inserts the code via the $.html function. So I can't access elements of the document by their ID from the script evaluated by the $.html.
Is there any solution to pass JavaScript code through the Form/Ajax API?
I think jQuery("#new-id") (not $(..)) should take the newest dom elements.
You can use either the 'ajax' property of form api
$form['myitem'] = array(
'#type'=>'textfield',
'#ajax' => array(
'callback' => 'my_callback',
'wrapper' => 'new-id',
'method' => 'html',
'effect' => 'fade',
),
);
$form['myitem2'] = array(
'#type'=>'markup',
'#value'=>"<div id='new-id'> I'm #new-id </div>"
);
function my_callback(&$form, &$form_state){
$commands = array();
$commands[] = ajax_command_invoke('#new-id', 'html', array('<div id="new-id2">#new.id2 here!</div>'));
$commands[] = ajax_command_invoke('#new-id2', 'addClass', array('error'));
return array('#type' => 'ajax', '#commands' => $commands);
}
D7 ajax_commands:
http://api.drupal.org/api/drupal/includes--ajax.inc/group/ajax_commands/7
hope this help

Resources