CakePHP 3 - Deleting associated data using ajax - javascript

Posts can have multiple authors.
I want to add the possibility to delete authors in a post using Ajax.
PostsAuthorsTable.php
$this->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
PostsTable.php
$this->hasMany('PostsAuthors', [ 'foreignKey' => 'post_id' ]);
PostsController.php
public function delete_author($authorID)
{
$id = $_GET['authorID'];
$this->Posts->PostsAuthors->delete($id);
$this->autoRender = false;
}
View: Posts > edit.ctp (JavaScript part)
<?php $this->start('script'); ?>
<script>
$(document).ready(function () {
$('.delete-author').on('click', function () {
$.ajax({
url: '<?= $this->Url->build(["action" => "delete_author"]) ?>',
type: 'GET',
data: { authorID: $(this).data('id') }
});
return false;
});
});
</script>
<?php $this->end(); ?>
View: Posts > edit.ctp (HTML part)
<?php foreach ($post_authors as $post_author): ?>
<tr>
<td><?= $post_author->user->name ?></td>
<td class="text-center">
<a href="#" class="delete-author text-danger" data-id="<?= $post_author->id ?>">
<i class="icon-trash"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
Thank you for your help. :)

I found the solution.
PostsController.php
public function delete_author($authorID)
{
$id = $_GET['authorID'];
$entity = $this->Posts->PostsAuthors->get($id);
$this->Posts->PostsAuthors->delete($entity);
$this->autoRender = false;
}

Related

Wordpress Category Filtering Stuck

Everytime I click a category it shows only "Filtering..." and not loading all the post.
Filtering Issue
HTML
<div class="filters"> <span class="filter active" data-set="all"><span>Show all</span></span> <?php $categories = get_categories(array( 'hide_empty' => true, 'exclude' => array(1, 143) )); foreach ($categories as $category) : ?> <span class="filter" data-set="<?= $category->slug ?>"><span><?= $category->name ?></span></span> <?php endforeach; ?> </div>
SCRIPT
`(($) => {
const filters = $("#filterBar .filters");
const articles = $("#all-posts .articles");
filters.children('.filter').click(function(e) {
e.preventDefault();
const button = $(this),
loader = $("#loader"),
data = {
'action': 'filterposts',
'category': $(this).data('set')
};
$.ajax({
url : latest_reads_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
articles.html("<span class='message'>Filtering...</span>");
loader.remove();
filters.find('.active').removeClass('active');
button.addClass('active');
},
success : function( data ){
if( data ) {
data = JSON.parse(data);
articles.hide().html(data.posts).slideDown(400);
if (data.max_pages > 1) {
articles.after('<div id="loader">'+
'<span class="ibtn secondary large" id="loaderAction" data-category="'+data.category+'" data-maxpages="'+data.max_pages+'">Load more</span>'+
'</div>');
}
} else {
articles.html("<span class='message'>No post found for filter</span>");
}
}
});
});
})(jQuery);`
I wanted to display all category post

php constants in a javascript file | Add PHP Inside JS

I'm working on a Quiz project. It needs modification constants in javascript files.
const questions=[
{
q:'where is the capital of India',
options:['New Delhi','Kolkatta','Varanashi','Agra'],
answer:1
},
{
q:'Who is the Prime Minister of India',
options:['Amit Shah','Narendra Modi','Rahul Gandhi','None of the above'],
answer:2
},
{
q:'where is the capital of India',
options:['New Delhi','Kolkatta','Varanashi','Agra'],
answer:1
}
]
But we need to add PHP on constant.
Try this, but not working...
const questions=[
{
q:'<?php echo the_field("q_1"); ?>',
options:['(<?php echo the_field("option_1"); ?>)','(<?php echo the_field("option_2"); ?>)','(<?php echo the_field("option_3"); ?>)','(<?php echo the_field("option_4"); ?>)'],
answer:'<?php echo the_field("answer_1"); ?>'
},
{
q:'<?php echo the_field("q_2"); ?>',
options:['<?php echo the_field("option_1_2"); ?>','<?php echo the_field("option_2_2"); ?>','<?php echo the_field("option_3_2"); ?>','<?php echo the_field("option_4_2"); ?>'],
answer:'<?php echo the_field("answer_2"); ?>'
},
{
q:'<?php echo the_field("q_3"); ?>',
options:['<?php echo the_field("option_1_3"); ?>','<?php echo the_field("option_2_3"); ?>','<?php echo the_field("option_3_3"); ?>','<?php echo the_field("option_4_3"); ?>'],
answer:'<?php echo the_field("answer_3"); ?>'
}
]
Here is the full code
If you print your JavaScript using PHP you could achieve the same result using the following code:
<?php
$questions = [
[
q => the_field("q_1"),
options => [
the_field("option_1"),
the_field("option_2"),
the_field("option_3"),
the_field("option_4")
],
answer => the_field("answer_1")
],
[
q => the_field("q_2"),
options => [
the_field("option_1_2"),
the_field("option_2_2"),
the_field("option_3_2"),
the_field("option_4_2")
],
answer => the_field("answer_2")
],
[
q => the_field("q_3"),
options => [
the_field("option_1_3"),
the_field("option_2_3"),
the_field("option_3_3"),
the_field("option_4_3")
],
answer => the_field("answer_3")
],
// ... more options here
];
$output = [];
foreach($questions as $question) {
$q = new stdClass();
$q->q = $question['q'];
$q->options = $question['options'];
$q->answer = $question['answer'];
array_push($output, $q);
}
and then, later in your HTML do something like that:
<script type="text/javascript">
const $questions = <?php echo json_encode($output); ?>;
console.log($questions);
</script>

How to submit multipart form in Yii2?

I have a problem with my form because it cant serialize the image file. So how can I submit a form that contains an image file input in Yii2 using ajax?
(Below you can see the active form and the js code.)
<div class="cars-form">
<?php $form = ActiveForm::begin(['options'=>['id'=>$model->formName(),'enableAjaxValidation'=>true,'enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($model, 'colour')->widget(ColorInput::classname(), ['options' => ['placeholder' => 'Select Color...'],]); ?>
<?=$form->field($model, 'imageFile')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],'pluginOptions' => [
'previewFileType' => 'image',
'showUpload' => false],]);?>
<?= $form->field($model, 'price')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit',function(e)
{var \$form =$(this);
$.post(
\$form.attr("action"),
\$form.serializefiles()
)
.done(function(result)
{
if (result == 1)
{
$(\$form).trigger("reset");
$.pjax.reload({container:'#cars'});
}
else
{
$("#message").html(result);
}
}).fail(function(data)
{console.log("server error: " + data);});
return false;
});
JS;
$this->registerJs($script);?>
(Controller)
public function actionCreate()
{
$model = new Cars();
if ($model->load(Yii::$app->request->post())) {
$imageName= $model->name;
$model->imageFile= UploadedFile::getInstance($model,'imageFile');
$model->imageFile->saveAs('carsimages/'.$imageName.'.'.$model->imageFile->extension);
$model->image='carsImages/'.$imageName.'.'.$model->imageFile->extension;
if($model->save())
//{
//return $this->redirect(['view', 'id' => $model->id]);
//}
{
echo 1;
}
else
{
echo 0;
}
}
else {
return $this->renderAjax('create', [
'model' => $model,
]);
}}

Can't show success message after saving data from yii2 ActiveForm (in modal)

On main page I've got a button which call bootstrap modal with activeform. On submit this form adds new row in my db. But I dont look a success message neither in this modal nor on the main page. Instead I get to page mysite.ru/category/create with white screen and text of dialog message on it ("Dialog contents here..."). How not to redirect user on other page? Just close modal and/or redirect on main page and show here flashmessage about successful adding row.
my button in views/site/index.php:
<?= Html::button(
'create',
['value' => Url::to(['category/create']),
'id' => 'modalButton'
]) ?>
<?php
Modal::begin([
'id' => 'modal'
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
my controller SiteController has:
public function actionIndex()
{
return $this->render('index');
}
CategoryController has
public function actionCreate()
{
$model = new Category;
if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
$model->refresh();
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
} elseif ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('contactFormSubmitted');
//$model->refresh();
$this->refresh();
Dialog::begin([
'clientOptions' => [
'modal' => true,
],
]);
echo 'Dialog contents here...';
Dialog::end();
//$this->redirect('category/create');
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
views/category/create.php:
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\Category */
$this->title = 'Create Category';
$this->params['breadcrumbs'][] = ['label' => 'Categories', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="category-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
and views/category/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\jui\Dialog;
/* #var $this yii\web\View */
/* #var $model app\models\Category */
/* #var $form yii\widgets\ActiveForm */
?>
<?php
$this->registerJsFile(Yii::getAlias('/scripts/main.js'));
?>
<?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>
<div class="alert alert-success">
Thank you for contacting us. We will respond to you as soon as possible.
</div>
<?php endif; ?>
<div class="category-form">
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
//'enableAjaxValidation'=>true,
'validateOnSubmit'=>true,
//'action' => '/site/index'
]); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
scripts/main.js:
// listen click, open modal and .load content
$('#modalButton').click(function (){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
// serialize form, render response and close modal
function submitForm($form) {
$.post(
$form.attr("action"), // serialize Yii2 form
$form.serialize()
)
.done(function(result) {
form.parent().replaceWith(result);
//$form.parent().html(result.message);
//$('#modal').modal('hide');
})
.fail(function() {
console.log("server error");
$form.replaceWith('<button class="newType">Fail</button>').fadeOut()
});
return false;
}
You have to prevent your form from being submited and use ajax.
$(your_form)
.on('beforeSubmit', function(event){
event.preventDefault();
submitForm($(your_form));
return false;
})
.on('submit', function(event){
event.preventDefault();
});

DataTables Server Side Processing Adding html content select tag not triggering javascript

I have implemented successfully the datatables server side processing on one of my tables just that the $('.select_users').change(function(event){ doesn't work anymore on my select tab, despite the fact it shows correctly. When I try to select an option from the select tag it should action to the jquery function but it doesn't.
EDIT 28 NOV 2014
I have found that there is an issue with the events and server side processing:
http://www.datatables.net/examples/advanced_init/events_live.html.
So how can I convert script BLOCK #1 to match the script from the above link.
I added the
$('#dataTables-ss').on('click', 'tr', function () {
var name = $('td', this).eq(0).text();
alert( 'You clicked on '+name+'\'s row' );
} );
And this was getting triggered.
BLOCK #1 => Jquery - on change of select it should trigger this function
$('.select_users').change(function(event){
var selected_value = this.value;
var id = $(this).find('option:selected').attr('class');
var id = id.split('-');
var select_id = id[1];
$.ajax({
type: 'post',
url: 'includes/ajax.html',
data: {
action: 'confirm_notconfirm_subscribers',
selected_value: selected_value,
select_id: select_id
},
success: function(data) {
$('#message').html(data).fadeIn(1000).fadeOut(1000);
},
error: function() {
$("#result").html('There was an error');
}
});
});
BLOCK #2 => PHP important part
public function read_subscriber_table() {
$table = 'subscribers';
$primaryKey = 'ID';
$columns = array(
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'email', 'dt' => 2 ),
array( // issue is here in the third array where I create the select string.
'db' => 'confirmed',
'dt' => 3,
'formatter' => function( $d, $row ) {
if ($d == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($d !== '1') { $selected = 'selected'; } else { $selected = ''; }
$string = '<select class="select_users form-control" name="status-users">
<option class="opt-'.$row["ID"].'" value="1" '.$selected.'>Confirmed</option>
<option class="opt-'.$row["ID"].'" value="0" '.$selected.'>Not Confirmed</option>
</select>';
return $string;
}
),
array(
'db' => 'date',
'dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'd-m-Y', strtotime($d));
}
),
array(
'db' => 'ID',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '<input type="checkbox" class="checkbox_subscribers" value="'.$d.'" >';
}
)
);
$sql_details = $this->dtss_processing();
require( 'ssp.class.php' );
$result = SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns );
$start=$_REQUEST['start'] + 1;
foreach($result['data'] as &$res){
$res[0]=(string)$start;
$start++;
}
echo json_encode($result);
}
BLOCK #3 => Datatables initialized script
$(document).ready(function() {
$('#dataTables-ss').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "includes/data_tables.html?action=read_subscriber_table",
"aaSorting": [[4, 'desc']]
} );
} );
BLOCK #4 => EDIT - before implementing server side the function was looking like this and it was working well.
public function read_subscriber_table() {
$col_names = array('ID', 'name', 'email', 'confirmed', 'date');
$this->read_table('subscribers', $col_names);
$i = 0;
foreach ($this->results as $item) {
$i++;
if ($item->confirmed == '1') {
$confirmed = 'Confirmed';
} else {
$confirmed = 'Not Confirmed';
}
if ($item->confirmed !== '1') { $selected = 'selected'; } else { $selected = ''; }
?>
<tr id="tablerow-<?php echo $item->ID; ?>">
<td><?php echo $i; ?></td>
<td><?php echo $item->name; ?></td>
<td><?php echo $item->email; ?></td>
<td>
<select class="select_users form-control" name="status-users">
<option class="opt-<?php echo $item->ID; ?>" value="1" <?php echo $selected ?>>Confirmed</option>
<option class="opt-<?php echo $item->ID; ?>" value="0" <?php echo $selected ?>>Not Confirmed</option>
</select>
</td>
<td><?php echo $item->date; ?></td>
<td><input type="checkbox" class="checkbox_subscribers" value="<?php echo $item->ID; ?>" ></td>
</tr>
<?php
}
?>
<?php
}
Follwing on from comments...
Using that updated code as a starting point, change $('#dataTables-ss').on('click', 'tr', function () { to $('#dataTables-ss').on('change', '.select_users', function(event){

Categories