So basically I have a controller that handles files (images & videos) and on the "view" view I have a button that's called "view content". That button is using the controller actionContent($id) and I want it when pressed to run the AJAX call to the action & render in-page in a div the image that's located in the model with id == $id. How can I handle the AJAX request and return the image displayed in the div?
public function actionContent($id)
{
$model = $this->findModel($id);
switch (substr($model->mime, 0, strpos($model->mime, '/'))) {
case 'image' :
return $this->renderAjax('_image', [
'img' => $model->getFullPath(),
]);
break;
default:
break;
}
}
And the view:
<span class="pull-right">
<?= Html::a('View Content', ['content', 'id' => $model->id], [
'class' => 'btn btn-default',
'id' => 'content'
]); ?>
</span>
With the script I already tried:
$(document).ready(function () {
$('#content').click(function () {
$(this).preventDefault();
$.ajax({
type: "GET",
url: $(this).href,
contentType: "<?= $model->mime?>",
success: function (response) {
('.show-content').html('<img src="data:image/png;base64,' + response + '" />');
}
})
})
})
Related
on Yii2 Advanced My form insert twice in table, if I click twice my submit button my form insert data to my table twice it's like I clicked two time on my submit button; I'm using ajax for submit my form; my form in view is
<script type="text/javascript">
$(document).ready(function (e) {
$("#upload-gallery").on('submit',(function(e) {
$form = $(this);
e.preventDefault();
$.ajax({
url: $form.attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
document.getElementById("upload-gallery").reset();
$.pjax.reload({container: '#some_pjax_id', async: false});
},
error: function(){}
});
}));
});
</script>
<div class="post-gallery-form">
<?php $form = ActiveForm::begin(['id' => 'upload-gallery', 'options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model_PstGlr, 'PGalleryFile[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<?= $form->field($model_PstGlr, 'post_text')->textarea(['rows' => 2]) ?>
<?= $form->field($model_PstGlr, 'permission_id')->dropdownList($model_Permission->PermissionOn()) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
and my controller is
public function actionView($chn)
{
$model_Permission = new Permission;
$model_PstGlr = new PostGallery; $acc_PstGlr = new AxPostGallery;
if ($model_PstGlr->load(Yii::$app->request->post()) )
{
$acc_PstGlr->CreateGallery($model_PstGlr, $chn);
}
return $this->render('view', [
'model' => $this->findModel($chn),
'model_Permission' => $model_Permission,
'model_PstGlr' => $model_PstGlr,
]);
}
The upload gallery function is to upload images on my contents
--
public function CreateGallery ($MPGALLERY, $CHNID)
{
$PSTID = Yii::$app->params['PSTID'];
$USRID = Yii::$app->user->id;
$MPGALLERY->post_id = $PSTID;
$MPGALLERY->user_id = $USRID;
$MPGALLERY->channel_id = $CHNID;
$ly_lgIMGFolder = 'upload/gal/'. $CHNID . '/' . $PSTID . '/' .date('YzHis');
$GLRID = Yii::$app->params['GLRID'];
$MPGALLERY->PGalleryFile = UploadedFile::getInstances($MPGALLERY, 'PGalleryFile');
if( $MPGALLERY->save() )
{
mkdir($ly_lgIMGFolder, 0777, true);
foreach ($MPGALLERY->PGalleryFile as $GImage)
{
$MGALLERY = new Gallery;
$MGALLERY->post_id = $PSTID;
$GImage->saveAs($ly_lgIMGFolder ."/". $GLRID . '.' . $GImage->extension);
$MGALLERY->gallery_lgimage = $ly_lgIMGFolder ."/". $GLRID . '.' . $GImage->extension;
$MGALLERY->save(false);
}
}
}
Appatently, there are a few changes that you may need to make in your code.
For example, create the following function in your controller, and remove the code from your view.
public function actionSave(){
//This part is removed from the actionView, so that the request only saves and does nothing else;
//You can return it back if you test and see that it works
$model_PstGlr = new PostGallery; $acc_PstGlr = new AxPostGallery;
if ($model_PstGlr->load(Yii::$app->request->post()) )
{
$acc_PstGlr->CreateGallery($model_PstGlr, $chn);
}
}
Then on the view, modify your form initialization as follows
The reason for adding the forwad slash is to prevent apache from sending the request to a new URL that ends with the '/';
<?php $form = ActiveForm::begin(['action'=> 'id' => 'upload-gallery', 'options' => ['enctype' => 'multipart/form-data']]) ?>
I hope this one now helps;
I don't want to submit a form but i want to get the value of a input field and send it to controller via ajax to be save in database.
I have this below JS code to help me get the content of the input field and send to the server side after 3 second of user input
<?php
$script = <<< JS
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var \$TitleInput = $('#product-product_title');
//on keyup, start the countdown
\$TitleInput.on('keyup input change paste',function(){
clearTimeout(typingTimer);
if (\$TitleInput.val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: data,
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});
JS;
$this->registerJs($script);
?>
in my controller i have this
public function actionCreate()
{
$model = new Draft();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \time();
if($model->save()){
echo draftId;
}else{
echo '0';
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I want to echo back the draftid if the title was draft was save successfully
how to make this work plase any help on this
below is my view
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'enableClientValidation' => true,
'fieldConfig' => ['template' => '{label}{input}{hint}']
]); ?>
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'product_title')->textInput([
'class' => 'title-input',
'placeholder' => 'Give us a title for your items(include size,brand,color,material. e.t.c)',
])->label(false) ?>
</div>
<div class="col-md-12 text-muted">E.g Men's blue addidas glide running shoes size 11 </div>
</div>
<?= $form->field($model, 'user_id')->textInput() ?>
<?= $form->field($model, 'product_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'category_id')->textInput() ?>
i have this in my view but i would like to only save the value of the first input field after 3 second that user entered there value
Try this JS, but change $('#form') on your ID form
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var $form = $('#form');
//on keyup, start the countdown
$form.find('input[type="text"]').on('keyup input change paste',function(){
clearTimeout(typingTimer);
if ($(this).val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: $form.serialize(),
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});
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.
I'm using Yii2's advanced template, and looking for a way to display a dialog with 'Please wait...' message while sending an login form to the server.
Here is my active form code:
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
]); ?>
<fieldset>
<?= $form->field($model, 'username', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('username'),
],
])->label(false); ?>
<?= $form->field($model, 'password', [
'inputOptions' => [
'placeholder' => $model->getAttributeLabel('password'),
],
])->label(false)->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-lg btn-success btn-block', 'name' => 'login-button']) ?>
</fieldset>
<?php ActiveForm::end(); ?>
And my server side action:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
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()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
I'm successfully validating the inputs / sending the form, but need to display a dialog, so if the connection is slow the user will get an idea that the form is actually sending and needs more time to complete.
For ActiveForm you need to use according events. Currently it's managed with Javascript (see official upgrade info).
$('#myform').on('ajaxBeforeSend', function (event, jqXHR, settings) {
// Activate waiting label
}).on('ajaxComplete', function (event, jqXHR, textStatus) {
// Deactivate waiting label
});
Here is more detailed info about these two events.
ajaxBeforeSend:
ajaxBeforeSend event is triggered before sending an AJAX request for
AJAX-based validation.
The signature of the event handler should be:
function (event, jqXHR, settings)
where
event: an Event object.
jqXHR: a jqXHR object
settings: the settings for the AJAX request
ajaxComplete:
ajaxComplete event is triggered after completing an AJAX request for
AJAX-based validation. The signature of the event handler should be:
function (event, jqXHR, textStatus)
where
event: an Event object.
jqXHR: a jqXHR object
textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").
Also check this extension, maybe it will be useful for this purpose.
Please use the following javascript solution to listen to 'before submit'
$('body').on('beforeSubmit', 'form#yourFormId', function() {
$('#loading').show(); //show the loading div
var form = $(this);
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(data) {
// do processing of data
$('#loading').hide(); //hide it
}
});
return false;
});
You will need to add a div with id loading and use suitable css for that
<div id='loading'> Loading ... </div>
Adding a maunal close button to this div is also recommended for cases with network fluctuations
I am new in code Igniter so I don't know how to do it. So what my problem is I have a form which I am submitting from ajax. So what I want to do is as the form submit successfully then a notification or a css div class will appear above the form and then disappear it.I don't know how can I perform this as after accepting the parameter from view page to controller I don't know how to send the parameter controller to view or how can I perform all this .Here is my controller:
class categoryController extends CI_Controller {
function index(){
$data['main_content'] = 'categoryView';
$this->load->view('dashboardTemplate/template',$data);
}
function addCategory(){
//getting parameters from view
$data = array(
'cat_name' => $this->input->post('cat_name')
);
$is_ajax = $this->input->post('ajax'); //or use this line
$this->load->model('categoryModel');
$query = $this->categoryModel->addCategories($data);
if ($query && $is_ajax){
$page['main_content'] = 'categoryView';
$page['v'] = '1'; // i dont know how this variable is not accessing in view page by echo $v
$this->load->view('dashboardTemplate/template',$page);
}
else
{
//
}
}}
Here is my view:
<?php
$attributes = array('id' => 'form-horizontal',
'class' => 'form-horizontal'
);
echo form_open('categoryController/addCategory', $attributes);
$cat_name = array(
'name' => 'cat_name',
'id' => 'cat_name',
'class' => 'cat_name');
$button = array(
'name' => 'button',
'id' => 'btn',
'class' => 'btn btn-primary',
'value' => 'submit',
'type' => 'submit',
'content' => 'Submit'
);
?>
<h3>Add Category</h3>
//here i want to do this .. that if form is submitted succesfully then this class will load only and the whole page remain the same
<div> class="alert-heading">sucess or not success!<div>
</div>
<div class="control-group">
<label for="basicround" class="control-label">Category Name:</label>
<div class="controls">
<?php echo form_input($cat_name); ?>
<div class="form-actions">
<?php echo form_button($button); ?></div>
<script type="text/javascript">
$('#btn').click(function() {
var cat_name = $('#cat_name').val();
if (!cat_name || cat_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
cat_name: $('#cat_name').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('categoryController/addCategory'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
</script>
Since it is an Ajax submit, So you need to pass JSON array from controller to view
echo json_encode($page);
Controller
$page['main_content'] = 'categoryView';
$page['v'] = '1'; // i dont know how this variable is not accessing in view page by echo $v
echo json_encode($page);
For the above step, you need to define
data-type:JSON
in your ajax function.
Ajax Function
$.ajax({
url: "<?php echo site_url('categoryController/addCategory'); ?>",
type: 'POST',
data: form_data,
data-type: "json",
success: function(msg) {
// Here you can access the values from controller like msg.v
$('#message').html(msg);
}
});
Based on the response, you can show the success message using
$(".alert-heading").show();