Pjax and form submit not woking in yii2 - php

I'm developing a registration page but some part of this page should be submitted alone. I make some research and found Pjax in yii2 ut what I found in the documentation not working properly with mine.
No tag is created...only a hidden element containing csrf.
On submission, All page is reloaded.
View:
<div class="row profileimg">
<?php Pjax::begin(['timeout' => 40000, 'id' => 'myPjax',]); ?>
<?= Html::beginForm(['couple-partner/saveprofileimg'], 'post', ['id' => 'CouplePartnerSumb', 'data-pjax' => true, 'class' => 'form-inline']); ?>
<div class="col-lg-12" onmouseover="onmouseOverImg('FirstPartnerEditButton', 'FirstPartnerDelButton');" onmouseout="onmouseoutImg('FirstPartnerEditButton', 'FirstPartnerDelButton')" id="imgdiv" style="display:inline-block;position: relative;left : 35%;height: 110px;width: 150px;">
<img src="<?= $models != NULL && sizeof($models) > 0 && $models[0]->USER_PROFILE_PIC != NULL ? $models[0]->USER_PROFILE_PIC : "" ?>" style="cursor: pointer;width:100%;height:100% " id="firstPartnerProfilePic" class="img-thumbnail ">
<?= Html::fileInput('imageFile', '') ?>
<?php echo Html::submitButton('Upload', ['class' => 'btn btn-primary', 'id' => 'submit_iddddd',]) ?>
</div>
<?php echo Html::endForm();Pjax::end();?>
</div>
Controller:
public function actionSaveprofileimg() {
$model = new CouplePartner();
if (Yii::$app->request->isAjax) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->renderAjax('index', ['model' => $model]);
}
I can't find what is the problem that Pjax not working properly and why submit button reload all the page when is clicked.

The page reloaded because controller throw 500 error.
You should change
$model->upload()
to
$model->imageFile->upload()
and try catch more issues while controller is processing upload request

Related

yii2 form AJAX to different action url

I am not able to make it work:
also it is always redirecting to `action/create' whereas i want to not to redirect to that action.
my code is like this in footer view:
<script>
jQuery(document).ready(function($) {
$("#quick-contact").on('submit',function(event) {
// $("#quick-contact").on('beforeSubmit',function(event) {
event.preventDefault(); // stopping submitting
console.log("step1");
var form = $(this);
var formData = form.serialize();
// var data = $(this).serializeArray();
var url = $(this).attr('/quick-contact/create');
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
dataType: 'json',
data: formData
})
.done(function(response) {
if (response.data.success == true) {
alert("Wow you commented");
}
})
.fail(function() {
console.log("error");
});
// return false;
});
});
</script>
<?php //pjax::begin(['enablePushState' => false]); ?>
<div id="contact-form">
<?php $form = ActiveForm::begin(['action'=>'/quick-contact/create','id'=>'quick-contact','method'=>'post']); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'message')->textarea(['rows' => 2]) ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<div id="quick-contact-form">
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>
// display error message
<?php if (Yii::$app->session->hasFlash('error')): ?>
<div class="alert alert-danger alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<h4><i class="icon fa fa-check"></i>Saved!</h4>
<?= Yii::$app->session->getFlash('error') ?>
</div>
<?php endif; ?>
</div></div>
<?php // pjax::end(); ?>
and in controller action like:
public function actionCreate()
{
$model = new QuickContact();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
var_dump($_POST);
if ($model->load(Yii::$app->requset->post()) && $model->save()) {
Yii::$app->session->setFlash('success','Thanks We will get in touch with you');
// $st = Yii::$app->getTable;
// $email_template = $st->email_template(1);
Yii::$app->mailer->compose()
->setTo('info#mywebsolutions.co.in')
->setFrom(['info#mywebsolutions.co.in'])
->setSubject('QuickContact')
->setHtmlBody('Request from - '.$model->name.'<br>'.'Email - '.$model->email. '<br>'.'Message - '.$model->message)
->send();
/* Yii::$app->mailer->compose('template', ['id' => 1, 'email_template' => $email_template, 'sender_name'=>$model->name,'message'=>$model->address])
->setTo($this->email)
->setFrom([$email => "vedic"])
->setSubject($this->subject)
//->setHtmlBody('Hi '.$this->name.'<br>'.'Welcome to Nexgen'.'<br>'.'We confirm of having received your Enquiry/feedback as below'.'<br>'.$this->body )
->send();
*/
}else{
Yii::$app->session->setFlash('error','There was an error in submission.');
}
//return $this->render('/site/index');
}
// return $this->renderPartial('/site/index');
}
updated jquery script code:
Now ajax request is going through, but the response I am getting is like:
name Unknown Property
message Getting unknown property: yii\web\Application::requset
code 0
type yii\base\UnknownPropertyException
file /var/www/clients/client2/web238/web/vendor/yiisoft/yii2/base/Component.php
just replace the
$("#quick-contact").submit(function(event) {
with
$("#quick-contact").on('beforeSubmit',function(event) {
Update
The reason you are getting the error is because you have several errors in your console regarding the 3rd party scripts, and until unless you remove them you wont be able to get it working, you need to fix the following
Another thing that is missing is the return false; statement in your beforeSubmit event you should add this line after the ajax call, to prevent form submission.
$("#quick-contact").on('beforeSubmit',function(event) {
//....your code for ajax call
return false;
});
Update 2
The reason for the error is the spelling for the requset which should be rather request you need to change the line
if ($model->load(Yii::$app->requset->post()) && $model->save()) {
to
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if you still into problems please add a separate question as this question addresses the ajax part only which is solved already.

Codeigniter data from view to controller

Each User has multi profiles. once they logged in, they are asked to select a profile,
here is the code for Form to select profile.
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 align ="center" class="panel-title">Select Profiles</h3>
</div>
<div class="panel-body">
<?php
foreach($resJacs->{'details'} as $key) {
echo form_open('selectaccess', array(
'class' => 'form-group',
'role' => 'form'
));
echo form_submit(array(
'value' => $key->profile_name,
'name' => $key->profile_type,
'class' => 'btn btn-lg btn-default btn-block'
));
echo form_close();
}
?>
</div>
</div>
</div>
</div>
when user selects the profile profile id is passed to session for later use. here is the code for "selectaccess",
public function SelectAccess() {
$sess_data = array(
'id' => $this->session->userdata['is_logged_in']['id'],
'prfid' => $this->input->post('')
);
print_r($sess_data);
}
how can i prfid as mentioned in selectaccess method.
I just want to give an example, maybe this can help u :
I am use pure html .
<form action="SelectAccess/<?php echo $id; ?>">
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
Controller
function SelectAccess($val='') {
$input = $this->input->post('name');
$_SESSION['whatever'] = $val;
}
Normally you need to know the name of the field in order to get the value at the controller. But you are dynamically creating the field names so that gets tricky.
Fortunately you are only posting one input so $_POST should have only one item. The way your view is written the value of $_POST[0] will be provided by $key->profile_name. Hopefully, that value is what you are looking for.
public function SelectAccess() {
{
$sess_data = array(
'id' => $this->session->userdata['is_logged_in']['id'],
'prfid' => isset($_POST[0])) ? $_POST[0] : NULL;
);
}

Yii2 Form Submission TroubleShoot

So I'm displaying the logged user's information on a page, followed by a form which can be used to change basic user info, such as e-mail address, username and so on.
In the ProfileController file, I have the Index action, which handles the user info and, theoretically, the form too:
public function actionIndex() {
$user = User::find()->where(['id' => Yii::$app->user->identity->id])->one();
if ($user->load(Yii::$app->request->post())) {
$user->save();
//var_dump($user->first_name);die;
}
return $this->render('index', [
'user' => $user,
]);
}
In the index view file, I'm displaying the form as it follows:
<div class="row form">
<div class="user-form col-md-8 col-md-offset-2">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($user, 'last_name')->textInput(['maxLength' => true]) ?>
<?= $form->field($user, 'first_name')->textInput(['maxLength' => true]) ?>
<?= $form->field($user, 'email')->textInput(['maxLength' => true]) ?>
<?= $form->field($user, 'image')->textInput([]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
Problem is, whenever I press the submit button beneath the form, the controller receives the post request, but does not update the new values given in the form fields, thus displaying the old info at the var_dump(). What should I do?
Probably validation failed. Proper way of doing this is:
// ...
if ($user->load(Yii::$app->request->post())) {
if ($user->save()) {
// validated and saved, check $user state now
}
}
Method save() calls method validate() automatically. You can call it on your own as well if you want to operate on this model only when it's validated.

Validate form by ajax in yii2

I have a form which is opening in popup so I want to validate my form by ajax validation but when i click on submit button my page getting refreshed so I am not getting any validation error
View file:
<?php $form = ActiveForm::begin([
'id' => 'signup-form',
'enableAjaxValidation' => true,
//'action' => Url::toRoute('user/ajaxregistration'),
'validationUrl' => Url::toRoute('user/ajaxregistration')
]); ?>
<div class="col-md-12">
<div class="formbox">
<div class="inputbox signup">
<div class="input-group"> <span class="input-group-addon"><i class="glyphicon name"></i></span>
<?= Html::textInput('userFullName', '', ['placeholder' => "Name",'class'=>'form-control']); ?>
</div>
<?php ActiveForm::end(); ?>
Controller File:
public function actionValidate() {
$model = new SignupForm;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model); \Yii::$app->end();
}
}
Model Code:
return [
['userFullName', 'trim'],
['userFullName', 'required'],
];
Please suggest me what should i do so that my page will not get refrsh and I will get the validation error
You are using an ActiveForm without any ActiveFields, this means that the validation rules that have been defined within the model aren’t even being assigned to the text input. I have written an implementation for your problem:
Model:
use Yii;
use yii\base\Model;
class ExampleForm extends Model
{
// this 'virtual attribute' defines a form field
public $userFullName;
// validation rules
public function rules()
{
return [
['userFullName', 'trim'],
['userFullName', 'required'],
];
}
}
Controller:
use models\ExampleForm;
use yii\web\Response;
use yii\widgets\ActiveForm;
public function actionExample()
{
$model = new ExampleForm;
// validate any AJAX requests fired off by the form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
// code to process form data goes here.. This will execute on a form submission.
}
return $this->render('example-form', [
'model' => $model,
]);
}
View:
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$this->title = 'Example';
?>
<div class="exampleForm">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the form.</p>
<!-- this form will submit via POST to the same action that renders it -->
<?php $form = ActiveForm::begin() ?>
<!-- this is an active field. Any validation rules for the 'userFullName' field -->
<!-- that have been defined within the $model object will be applied to this field -->
<!-- the validation has also been set to validate via ajax within the $options array -->
<!-- read more about ActiveFields here: http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html -->
<?= $form->field($model, 'userFullName', ['enableAjaxValidation' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit!', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The best way to see whether ajax requests are being sent off / the form is being validated is to check chromes developer tools, go to the network tab and inspect the activity.
use renderAjax() Method:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}else {
return $this->renderAjax('YourViewFileName', [
'model' => $model,
]);
}

Yii2 Display Error Messages Inside Modal

Here's how I implement my modal in my index.php view:
<?= Html::button(
'Change Password',
['value' => Url::to(['changepassword']). '&id=' . $session['user_id'],
'class' => 'btn btn-success',
'id' => 'modButton'
]) ?>
<?= Yii::$app->session->getFlash('message'); ?>
<?php
Modal::begin(['id' => 'modal2']);
echo "<div id='modContent'></div>";
Modal::end();
?>
And here is my modal form:
<?php $form = ActiveForm::begin(); ?>
<?= Yii::$app->session->getFlash('message'); ?>
</br>
<?= $form->field($model, 'password')->passwordInput(['value' => '', 'style' => 'width: 300px;'])->label('New Password') ?>
<?= $form->field($model, 'ConfirmNewPassword')->passwordInput(['value' => '', 'style' => 'width: 300px;']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Change Password', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
In my controller (just in case you'll be needing it):
if ($model->load(Yii::$app->request->post())) {
$model->password = sha1($model->password);
if($model->password !== sha1($model->ConfirmNewPassword)){
Yii::$app->session->setFlash('message', "Passwords don't match!");
return $this->redirect(['index']);
}
}
Every time I input an invalid password in my modal, the page redirects to the modal form in a separate page and there it displays the error message. I want that when the user inputs an invalid password, the modals stays with the error message somewhere inside it.
How do I do this?
Yes because you redirect to the "index" action if the password is not the same in Controller :
if($model->password !== sha1($model->ConfirmNewPassword)){
Yii::$app->session->setFlash('message', "Passwords don't match!");
return $this->redirect(['index']);
}
Should becomes :
if($model->password !== sha1($model->ConfirmNewPassword)){
Yii::$app->session->setFlash('message', "Passwords don't match!");
}
else {
return $this->redirect(['index']);
}

Categories