ajaxsubmit can't submit returns null - yii

I get an error 200. Form never gets posted, all fields return blank. I also checked if the columns are required, i set everything to null. I have another form that looks like this and it works fine. Any ideas?
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'thisForm',
)); ?>
//form
<?php
echo CHtml::ajaxSubmitButton('Add',
Yii::app()->createUrl("url/controller"),
array(
'type'=>'POST',
'dataType'=>'text json',
'data'=>'js:$("#thisForm").serialize()',
'success'=>'js:function(data) {
if(data.status=="success")
$.fn.yiiGridView.update("osb123");
}',
'error'=>'function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}'
));
?>
public function actionController()
{
$model=new Model;
if($_POST['Model'])
{
$model->attributes=$_POST['Model'];
$model->temporary_id = Yii::app()->user->user_id;
$model->cost = floatval($_POST['Model']['cost']);
$model->active = "Y";
if($model->validate()){
echo CJSON::encode(array('status'=> 'success',
'data'=>var_dump($_POST['Model'])
));
}
else{
$error = CActiveForm::validate($model);
echo CJSON::encode(array('status'=> 'error', 'error'=>var_dump($_POST['Model'])));
}
}else echo CJSON::encode(array('status'=>'error','error'=>'Not Set'));
}

In the ajax button for url you set: Yii::app()->createUrl("url/controller") while usually the right syntax is Yii::app()->createUrl("controller/action") Could you with debugging tool (Ctrl+Shift+I or F12) check the POST-request and see the actual url that has been generated by yii?
You have beginWidget, do you also have endWidget ?

Related

yii dependent dropdown is not working

This is my view page
<?php echo $form->dropDownListRow($order,'area_id',Area::model()->getActiveAreaList(),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/getdeliveryforarea'),
'update'=>'#pickup_time_slot', //selector to update
'data' => array('area_id' => 'js:this.value',),
)));
?>
<?php echo $form->dropDownListRow($order,'pickup_time_slot',array(),array('prompt'=>'Select time')); ?>
and in my controll the getdeliveryforarea is like
public function actionGetdeliveryforarea()
{
$data=Areatimeslot::model()->findAll('area_id=:area_id',
array(':area_id'=>(int) $_POST['id']));
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
here my dependent dropdown is not working ,from getActiveAreaList i will get the area list in first dropdown and once i choose an area it must show corrosponding time list in second dropdown,i hope someone will help me out,thanks in advance
Use Juqery migrate plugin or try something like,
jQuery.browser = {};
(function () {
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
})();

Unable to post data to survey controller in yii

index.php
<?php
Yii::app()->clientScript->registerScript('items_update',
"$('#dropit').change(function(){
$.ajax({
url: '".Yii::app()->createUrl('survey/questions')."',
data:
{
_designation : test,
},
type: 'POST',
success:function()
{
console.log('success');
},
error:function()
{
console.log('failure');
}
});
return false;
});
");
?>
<div id="surveyupdate">
<?php
echo CHtml::dropDownList('dropit', '',
array(
'Reception'=>'Service Reception',
'SA'=>'ServiceAdvisor','Billing'=>'Billing Staff',
'Parts'=>'Parts Counter','Cashier'=>'Cashier','Cwd'=>'Customer Welfare Desk'),
array('prompt'=>'- select -'));
?>
</div>
<?php
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'id'=>'ajaxListView',
));
?>
controller 'survey.php'
public function actionQuestions()
{
//debugging purposes
echo "<pre>";
print_r($_POST);
exit;
}
To Do's
What I'm trying to do is to update the CListView by getting the selected data from dropdownlist via POST that to be evaluated by the controller, get the data from database and update the CListview.
Please help me. I'm just newly learning Yii. Thanks!
You need to add Id for dropdownList, like below
echo CHtml::dropDownList('dropit', '',
array(
'Reception'=>'Service Reception',
'SA'=>'ServiceAdvisor','Billing'=>'Billing Staff',
'Parts'=>'Parts
Counter','Cashier'=>'Cashier','Cwd'=>'Customer Welfare
Desk'),
array('prompt'=>'- select -', 'id'=>'dropit')); // added I'd here

Why i getting an error "Call to a member function formName() on a non-object"

i try to save multilanguaged content
My About model
...
public function rules() {
return [
[['status', 'date_update', 'date_create'], 'integer'],
[['date_update', 'date_create'], 'required'],
];
}
...
public function getContent($lang_id = null) {
$lang_id = ($lang_id === null) ? Lang::getCurrent()->id : $lang_id;
return $this->hasOne(AboutLang::className(), ['post_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
}
My AboutLang model
public function rules()
{
return [
[['post_id', 'lang_id', 'title', 'content'], 'required'],
[['post_id', 'lang_id'], 'integer'],
[['title', 'content'], 'string'],
];
}
My About controller
public function actionCreate()
{
$model = new About();
$aboutLang = new AboutLang();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,'aboutLang'=>$aboutLang]);
}
}
and my view (create form)
...
<?= $form->field($model, 'status')->textInput() ?>
<?= $form->field($aboutLang, 'title')->textInput() ?>
<?= $form->field($aboutLang, 'content')->textInput() ?>
enter code here
And when i put $aboutLang in create form i get an error "Call to a member function formName() on a non-object"
It looks like the views you are using were generated by Gii. In that case, Gii generates a partial view for the form (_form.php) and two views both for create and update actions (create.php and update.php). These two views perform a rendering of the partial view.
The problem you might have is that you are not passing the variable $aboutLang from create.php to _form.php, that must be done in create.php, when you call renderPartial():
$this->renderPartial("_form", array(
"model" => $model,
"aboutLang" => $aboutLang, //Add this line
));
Hope it helps.
Check your $aboutLang type.
It looks like it is null.
if ($aboutLang) {
echo $form->field($aboutLang, 'title')->textInput();
echo $form->field($aboutLang, 'content')->textInput();
}

Custom validation rule is not working for CFormModel

My front end is Php Yii. I am trying to create a custom validation rule which checks to see if the username already exists in the database.
I don't have direct access to the database. I have to use the RestClient to communicate with the Database. My issue is that custom validation rule is not working with my CFormModel.
Here is my code:
public function rules()
{
return array(
array('name', 'length', 'max' => 255),
array('nickname','match','pattern'=> '/^([a-zA-Z0-9_-])+$/' )
array('nickname','alreadyexists'),
);
}
public function alreadyexists($attribute, $params)
{
$result = ProviderUtil::CheckProviderByNickName($this->nickname);
if($result==-1)
{
$this->addError($attribute,
'This Provider handler already exists. Please try with a different one.');
}
This doesn't seem to work at all, I also tried this:
public function alreadyexists($attribute, $params)
{
$this->addError($attribute,
'This Provider handler already exists. Please try with a different one.');
}
Even then, it doesn't seem to work. What am I doing wrong here?
The problem with your code is that it doesn't return true or false.
Here is one of my rules to help you:
<?php
....
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, link', 'required'),
array('title, link', 'length', 'max' => 45),
array('description', 'length', 'max' => 200),
array('sections','atleast_three'),
);
}
public function atleast_three()
{
if(count($this->sections) < 3)
{
$this->addError('sections','chose 3 at least.');
return false;
}
return true;
}
...
?>
I met the same issue and finally got it solved. Hopefully, the solution could be useful for resolving your problem.
The reasons why the customised validation function is not called are:
this is a server side rather than client side validation
when you click the "submit" button, the controller function takes over the process first
the customised function won't be involved if you didn't call "$model->validate()"
Therefore, the solution is actually simple:
Add "$model->validate()" in the controller function. Here is my code:
"valid.php":
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'alloc-form',
'enableClientValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true,),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'valid_field'); ?>
<?php echo $form->textField($model,'valid_field'); ?>
<?php echo $form->error($model,'valid_field'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
"ValidForm.php":
class ValidForm extends CFormModel
{
public $valid_field;
public function rules()
{
return array(
array('valid_field', 'customValidation'),
);
}
public function customValidation($attribute,$params)
{
$this->addError($attribute,'bla');
}
}
"SiteController.php"
public function actionValid()
{
$model = new ValidForm;
if(isset($_POST['AllocationForm']))
{
// "customValidation" function won't be called unless this part is added
if($model->validate())
{
// do something
}
// do something
}
}

Facebook Connect API issue with authentication token

I have implemented the following code below according to the documentation and can get it to connect and display user id...
<?php
define('FACEBOOK_APP_ID', '87939462878');
define('FACEBOOK_SECRET', '1ab6346bc51329831998985aba200935');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>
<?php if ($cookie) { ?>
Your user ID is <?= $cookie['uid'] ?>
<?php } else { ?>
<fb:login-button show-faces="true" perms="email,user_birthday,user_location"></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({appId: '<?= FACEBOOK_APP_ID ?>', status: true,
cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
</script>
<?php
$user = json_decode(file_get_contents(
'https://graph.facebook.com/me?access_token=' .
$cookie['access_token']))->id;
print_r($user);
?>
However, if I use:
$user = json_decode(file_get_contents(
'https://graph.facebook.com/me?wrap_access_token=' .
$cookie['oauth_access_token']))->me; //or $cookie['access_token']))->me;
register_user($user->id, $user->email, $user->name, $user->username,
$user->birthday_date);
to get the email address, I keep getting file_get_content errors. I also get errors saying it doesn't recognize the register_user function. I feel that I'm close!! Please help if possible, thanks!
I'm not familiar with the library you're using that has register_user, but is there any reason you aren't using the Facebook connect PHP SDK? You can download it at http://github.com/facebook/php-sdk and it has examples for both obtaining the auth token with extended permissions and then pulling all the user information you seem to want.