ajax not posting, always a blank post - php

I'm going nuts with this. I am requesting ajax call in several places, and none of these ajax calls are working correctly lately. Today I decided to start fresh on a new section with ajax call. It's the same thing with all the other ones. It's been days that ajax data is not posting to controller - always blank.
Here is one of them. I am trying to allow users to vote up/down on click on CButtonColumn {up}{down}. This view grid "_vote.php" is generated through renderPartial using TbTabs. On renderpartial I did set to true on the last param.
Okay, next the grid. Here it is:
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'type'=>'condensed',
'id'=>'vote',
'dataProvider'=>$dataProvider,
'template'=>"{items}",
'ajaxUpdate'=>true,
'columns'=>array(
array(
'class'=>'CButtonColumn',
'template' => '{up} {down}',
'buttons' => array(
'up' => array(
'label'=>'<i class="fa fa-thumbs-up"></i>',
'imageUrl'=>false,
'url'=>'Yii::app()->createUrl("prod/votecommentup", array("id"=>$data->primaryKey))',
'click'=>' function(){
$.fn.yiiGridView.update("vote", {
type:"POST",
url:$(this).attr("href"),
success:function(data) {
$.fn.yiiGridView.update(vote);
}
}',
),
'down'=> array(
'label'=>'<i class="fa fa-thumbs-down"></i>',
'imageUrl'=>false,
'url'=>'Yii::app()->createUrl("prod/votecommentdown", array("id"=>$data->primaryKey))',
'click'=>' function(){
$.fn.yiiGridView.update("vote", {
type:"POST",
url:$(this).attr("href"),
success:function(data) {
$.fn.yiiGridView.update(vote);
}
}',
),
),
),
),
)); ?>
Okay... next, the url "prod/votecommentup", which is the nearly identical as votecommentdown. Here it is:
public function actionVoteCommentUp($id){
$model = $this->loadModel($id);
if(isset($_POST['VoteThis']))
{
$model->attributes=$_POST['VoteThis'];
$model->prototype_review_id = $id;
$model->user_id = Yii::app()->user->user_id;
$model->vote = "Y";
echo CJSON::encode(array('status'=>'saved'));
}echo CJSON::encode(array('status'=>'not post')); //always give me a no post
}

I recommend testing your calls through something like Postman App for chrome. This will give you the ability to debug your API/AJAX calls independent of your view. Once you have ensured the API/AJAX is functioning correctly, you can then integrate it into the view. This allows you to decouple the debugging process and hopefully make things more transparent as to what is functional and what is not.

Related

Yii2 CKeditor not initialized when requested via ajax

I am trying to add a from with a CKeditor widget imbedded via an AJAX request. The request itself works fine and returns the general partial view as I want it. Except for the Ckeditor widget, a normal textbox is return instead.
When the item is added to the group and the page is reloaded, the same partialView is being rendered (in a foreach with all group-items) and this time the CKeditor is nicely in place.
Posted my controller, initialization of the CKeditor and Scipt with AJAX request below. (The CKeditor is inlcuded in the _ContentItemHtml view)
I have taken a look at this, but I cannot call any CKeditor functions from JS since it is loaded as a widget.
Controller Action
public function actionCreateHtml($contentitemgroupid)
{
$model = new ContentItemHtml();
if (isset(Yii::$app->request->post()['ContentItemHtml'])) {
$item = Yii::$app->request->post()['ContentItemHtml'];
$model->contentitemgroupid = $contentitemgroupid;
$model->title = $item['title'];
$model->body = $item['body'];
$model->save();
// return $this->redirect(['edit', 'id' => $model->contentitemgroupid]);
}
else
return $this->renderPartial('_ContentItemHtml', ['model' => $model]);
}
Active form in view:
echo $form->field($model, 'body')->widget(CKEditor::className(), [
'preset' => 'custom',
'clientOptions' => [
'height' => 200,
'toolbarGroups' => [
['name' => 'basicstyles', 'groups' => ['basicstyles', 'cleanup']],
['name' => 'paragraph', 'groups' => ['templates', 'list']],
['name' => 'mode']]
]])->label(false);
Script.js
$('#addNewContentItem').on('click', function (e) {
e.preventDefault();
var url = 'create-' + $('#itemSelector').val().toLowerCase() + '?contentitemgroupid=' + $('#itemSelector').attr('contentitemgroupid');
$.ajax({
type: 'POST',
url: url,
cache: false,
success: function(res) {
$('.contentItemsManager').append('<div class="ContentItemContainer row">' + res + '</div>');
AddSaveEventListener();
AddSaveMediafileEventListener();
AddRemoveEventListener();
}
});
});
Use renderAjax instead of renderPartial. From the docs:
[renderAjax] Renders a view in response to an AJAX request.
This method is similar to renderPartial() except that it will inject into the rendering result with JS/CSS scripts and files which are registered with the view. For this reason, you should use this method instead of renderPartial() to render a view to respond to an AJAX request.

update yii listview onchange of dropdown

I want to change pagesize of listview using dropdown. please help me to find solution.
I have read many article but not able to do this. can u find where I'm making mistake
I'm using following code.
code for index.php (view)
code for dropdownlist
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::dropDownList('CategoryMst_pagesize','20',
array('10'=>'10','20'=>'20','50'=>'50','100'=>'100'
),
array('class'=>'form-control',
/*'ajax'=>array(
'type'=>'GET',
'data'=>array('pagesize'=>'js:this.value'),
'ajaxUpdate':()
),*/
));
?>
<?php echo CHtml::endForm(); ?>
code for listview
<?php $this->widget('zii.widgets.CListView',array(
'id'=>'category_list',
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'summaryText'=>'{start} - {end} of {count} results',
));
?>
<?php
Yii::app()->clientScript->registerScript('category_update',
"$('#CategoryMst_pagesize').change(function(){
$.fn.yiiListView.update('category_list', {
data: $(this).serialize(),
}
);
});
return false;",
CClientScript::POS_READY);
?>
code in cotroller
public function actionIndex($pagesize=20)
{
$dataProvider=new CActiveDataProvider('CategoryMst',array(
'criteria'=>array(
),
'pagination'=>array(
'pageSize'=>$pagesize,
),
));
$this->render('index',array('dataProvider'=>$dataProvider));
}
You really should not be using $('#CategoryMst_pagesize').change use https://api.jquery.com/on/ instead.
Then from what I see you are not remembering the page size anywhere, after you change it 1 time, as soon as you go to another page it will revert back to what you had before. THis is how I do it:
1) First use something to remember the page size, because right now you do not. I personally recommend this one http://www.yiiframework.com/extension/esaverelatedbehavior/ as it is really, really, really good. It also remember your filters (priceless).
2) create a function for your controller that will just save the page size.
/**
* Saves the new page size for this particular model
*/
public function actionPageSize($pagesize)
{
\Yii::app()->user->setState($this->modelName() . '_pagesize', $pagesize);
}
3) create the dropdown for the pagesize, I use Select 2 but you can use a normal dropdown. same Idea
<?php $this->widget('MySelect2', array(
'name' => 'pageSize',
'data'=>array('10' => '10', '25' => '25', '50' => '50', '100' => '100'),
'options'=>array('allowClear' => false, 'minimumResultsForSearch' => 30),
'htmlOptions' => array(
'data-ajax-dropdown' => $this->createUrl('pageSize'),
'style' => 'width: 80px',
'options'=>array(
(Yii::app()->user->getState($this->modelName() . '_pagesize', Yii::app()->params['defaultPageSize']))=>array('selected'=>'selected')
))));?>
4) I autosubmit the dropdowns for the page size like you do, but I submit them to the function above not to the index page
/*==========================
AUTOSUBMIT DROPDOWNS FOR THE PAGE SIZE
==========================*/
$('#pageSize').live('change',function(e){
var element = $(this);
jQuery.ajax({
"type": "GET",
"url": $(this).attr("data-ajax-dropdown"),
"cache": false,
"data":{pagesize: $(this).val()}
})
.success(function ( response ) {
$.fn.yiiGridView.update(element.closest('.widget.table').find('div.grid-view').attr('id'));
$.jGrowl("Pagination changed", { life: 2000 });
});
});
PS: I know I should not use .live
5) In the search for the model just like you do I have
return new \CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>$this->getTableAlias(false,false) . '.name asc',
),
'pagination'=>array(
'pageSize'=> \Yii::app()->user->getState(get_class($this) . '_pagesize', \Yii::app()->params['defaultPageSize']),
),
));

Call Render Partial using time interval in YII

I want to update a div contents automatically with refresh whole page. So i did Ajax renderPartial in YII. Now I implement using AJAX button onclick
My code as follows
<?php
echo CHtml::ajaxButton ("Update data",
CController::createUrl("blog/UpdateAjax?url=$url"),
array('update' => '#inrscrn'));
?>
Now I want to render with in a time limit please help
Your question is not very clear. I suppose you want to setup an automatical & periodical refresh of the content within a div instead of clicking on the button.
This is the JavaScript you need on your page:
<script type="text/javascript">
timeout = 60 * 1000; // in Milliseconds -> multiply with 1000 to use seconds
function refresh() {
<?php
echo CHtml::ajax(array(
'url'=> CController::createUrl("blog/UpdateAjax?url=".$url),
'type'=>'post',
'update'=> '#inrscrn',
))
?>
}
window.setInterval("refresh()", timeout);
</script>
But it is not a good approach to send an URL to your controler, rather make a direct request to to make a special AJAX return of a controler which needs to return the correspondent data.
<?php
public function actionTest(){
if (isset($_REQUEST['AJAX']) || Yii::app()->getRequest()->getIsAjaxRequest()) {
$this->renderPartial(
'test',
array('model' => $model),
false,
true
);
} else {
$this->render(
'test',
array('model' => $model),
);
}
}
?>

ajaxOnValidation and ajaxSubmitButton in Yii not working together

I have a jQuery dialog popup form shown within an iframe on Yii. If the form validates, it needs to save and close, otherwise it needs to show with the errors. However, while the validateOnChange is working, the validateOnSubmit doesn't - clicking on submit just returns the output of the view, instead of the errors (or an empty array). I'm not really sure where to start with fixing it.
I have these options in the beginWidget() call:
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
And I am using this code to generate the button:
CHtml::ajaxSubmitButton('Submit', 'enter', array('success' => 'afterValidate()'));
I found a couple of other links talking about the problem of these two options not working together at: Yii ajaxSubmitButton() with fields validation and
http://code.google.com/p/yii/issues/detail?id=2008. However, I'm not sure what to do with the suggested fix in the last link:
function afterValidate(form, data, hasError){
if (!hasError) {
$.ajax({
url: '{$postUrl}',
type: 'POST',
dataType: 'json',
data:jQuery(this).parents("form").serialize()
})
.done(function ( response ) {
// my successhandler
})
.fail(function ( xhr, status ) {
// my error handler
});
return false;
}
}
The callback function is being called, but always fails, whether the data is valid or not.
So, how do I implement a jQuery dialog form in Yii?

Execute PHP Code via Ajax Call in drupal module

I was trying to convert this into a Drupal module so that I can check PHP code instantly on my site for debugging purposes. I saw this Firefox add on which allows you to execute PHP on the fly but admin log in is necessary, so far I did everything , have one form and set up ajax calls , but if I pass a string like:
preg_match($pat,$str,$matches);
print_r($matches);
How to execute this in backend?
EDIT
To load the form:
$items['localphp'] = array(
'page callback' => 'executePHP',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
function executePHP(){
$output = drupal_get_form('executePHP_form');
return $output;
}
Ajax callback function:
$items['runPHP'] = array(
'page callback' => 'getResult',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
function getResult(){
$code = $_POST['code'];
//I need help here how to execute $code i.e the php code and return back result
echo $code;
}
JS function
function executePHP(baseurl){
var code = $("#edit-code").val();
$.ajax({
type : "POST",
url : baseurl+'runPHP',
data : 'code='+code,
async : true,
cache : false,
success : function (res) {
$("#edit-result").html(res);
},
error : function (res) {
alert("error");
}
});
return false;
}
FYI, the Devel module has a feature that allows admins to run custom PHP code from their page. The Devel module has a block with a ton of features useful for debugging.
For a custom module, without seeing any of your other code, I can tell you what I have done to achieve AJAX in a Drupal module:
In JavaScript make an AJAX request to a url on your site. Add a menu item with the specified path inside of hook_menu() as 'type' => MENU_CALLBACK that points to a function in your module. This function should do all the processing you need, then return the results to JavaScript to do what you want with it there.

Categories