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
i´m traying to upload a video with dropzone, i did method in controller, view, model, trait, etc... But when i call my route to my function, returned me this:
Method Illuminate\Validation\Validator::validateVideo does not exist.
i understand where i have my problem...
i attachd my actual code:
route
Route::post('uploads/storeVideo', 'UploadController#storeVideo')->name('medias.createVideo');
Controller
public function storeVideo(UploadRequest $request)
{
$input = $request->all();
try {
$upload = $this->uploadRepository->create($input);
$upload->addMedia($input['file'])
->withCustomProperties(['uuid' => $input['uuid'], 'user_id' => auth()->id()])
->toMediaCollection($input['field']);
} catch (ValidatorException $e) {
return $this->sendResponse(false, $e->getMessage());
}
}
view
<div class="form-group row">
{!! Form::label('video', trans("lang.restaurant_video"), ['class' => 'col-3 control-label text-right ']) !!}
<div class="col-9">
<div style="width: 100%" class="dropzone video" id="video" data-field="video">
<input type="hidden" name="video">
</div>
{{ trans('lang.media_select')}}
<div class="form-text text-muted w-50">
{{ trans("lang.restaurant_video_help") }}
</div>
</div>
</div>
#prepend('scripts')
<script type="text/javascript">
var var15671147011688676454bleVideo = '';
#if(isset($restaurant) && $restaurant->hasMedia('video'))
var15671147011688676454bleVideo = {
name: "{!! $restaurant->getFirstMediaVideoUrl('video')->name !!}",
size: "{!! $restaurant->getFirstMediaVideoUrl('video')->size !!}",
type: "{!! $restaurant->getFirstMediaVideoUrl('video')->mime_type !!}",
collection_name: "{!! $restaurant->getFirstMediaVideoUrl('video')->collection_name !!}"
};
#endif
var dz_var15671147011688676454bleVideo = $(".dropzone.video").dropzone({
url: "{!! url('panel/uploads/storeVideo') !!}",
/*dictDefaultMessage: "{{trans('validation.dropzone_dictDefaultMessage')}}",
dictFallbackMessage: "{{trans('validation.dropzone_dictFallbackMessage')}}",
dictFallbackText: "{{trans('validation.dropzone_dictFallbackText')}}",
dictFileTooBig: "{{trans('validation.dropzone_dictFileTooBig', [ 'size' => config('medialibrary.max_file_size') / 1024 / 1024 ])}}",
dictInvalidFileType: "{{trans('validation.dropzone_dictInvalidFileType')}}",
dictResponseError: "{{trans('validation.dropzone_dictResponseError')}}",
dictCancelUpload: "{{trans('validation.dropzone_dictCancelUpload')}}",
dictCancelUploadConfirmation: "{{trans('validation.dropzone_dictCancelUploadConfirmation')}}",
dictRemoveFile: "{{trans('validation.dropzone_dictRemoveFile')}}",*/
dictMaxFilesExceeded: "{{ trans('validation.dropzone_dictMaxFilesExceeded') }}",
maxFilesize: {!! config('medialibrary.max_file_size_video') / 1024 / 1024 !!},
acceptedFiles: "video/*",
addRemoveLinks: true,
maxFiles: 1,
init: function () {
#if(isset($restaurant) && $restaurant->hasMedia('video'))
dzInit(this, var15671147011688676454bleVideo, '{!! url($restaurant->getFirstMediaVideoUrl('video','mp4')) !!}')
#endif
this.on("error", function(file, message) {
console.log(message);
$('.video').after(`<ul class="alert alert-danger" style="list-style: none;">
<li>
${message}
</li>
</ul>`);
this.removeFile(file);
});
this.on("success", function(file, message) {
$('.alert-danger').remove();
$('.video').after(`<ul class="alert alert-success" style="list-style: none;">
<li>
{{trans('validation.dropzone_success')}}
</li>
</ul>`);
});
},
accept: function (file, done) {
dzAccept(file, done, this.element, "{!! config('medialibrary.videos_folder') !!}");
},
sending: function (file, xhr, formData) {
dzSending(this, file, formData, '{!! csrf_token() !!}');
},
maxfilesexceeded: function (file) {
dz_var15671147011688676454bleVideo[0].mockFile = '';
dzMaxfile(this, file);
},
complete: function (file) {
dzComplete(this, file, var15671147011688676454bleVideo, dz_var15671147011688676454bleVideo[0].mockFile);
dz_var15671147011688676454bleVideo[0].mockFile = file;
},
removedfile: function (file) {
dzRemoveFile(
file, var15671147011688676454bleVideo, '{!! url("panel/restaurants/remove-media") !!}',
'video', '{!! isset($restaurant) ? $restaurant->id : 0 !!}', '{!! url("panel/uploads/clear") !!}', '{!! csrf_token() !!}'
);
}
});
dz_var15671147011688676454bleVideo[0].mockFile = var15671147011688676454bleVideo;
dropzoneFields['video'] = dz_var15671147011688676454bleVideo;
</script>
#endprepend
UploadRequest deault in laravel
public function rules()
{
return [
'file' => 'image|video|mimes:jpeg,png,jpg,gif,svg,mp4,mov,avi,mkv',
];
}
Model
// VIDEO AND ALLOWED TYPES
public function getFirstMediaUrlVideo($collectionName = 'default', $conversion = '')
{
$url = $this->getFirstMediaVideoUrlTrait($collectionName);
if($url){
$array = explode('.', $url);
$extension = strtolower(end($array));
if (in_array($extension, ['.mp4', '.mkv'])) {
return asset($this->getFirstMediaVideoUrlTrait($collectionName, $conversion));
} else {
return asset('videos/' . $extension . '.mp4');
}
}else{
return asset('videos/video_default.mp4');
}
}
thanks for all help, i don´t know why does this happen. Thanks
Your error, at least the first one, is here:
public function rules()
{
return [
'file' => 'image|video|mimes:jpeg,png,jpg,gif,svg,mp4,mov,avi,mkv',
]; ^^^^^
}
There is no video validation rule (you can check the full list here). What you should do, instead, is make use of the mimes (or mimetypes) rule alone:
return [
'file' => 'mimes:mp4,mov,avi,mkv',
];
For the full list of mime extensions that you could use, here's the list.
This implementation of dropzone.js works on my local host, but when I move it to live the files don't end up on the server:
Here's the form:
<form action="submit.php" enctype="multipart/form-data" method="POST">
<label for="fname">First name: </label>
<input type="text" name="fname" id="fname" required />
<label for="lname">Surname:</label>
<input type="text" name="lname" id="lname" required />
<div class="dropzone" id="file-upload"></div>
<button type="submit" id="submit-all">Submit</button>
</form>
I am using AJAX to submit the form:
$(document).ready(function() {
Dropzone.options.fileUpload = {
url: '/submit.php',
autoProcessQueue: false,
paramName: 'file',
uploadMultiple: true,
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 10,
acceptedFiles: 'image/*,.mp4,.mkv,.avi',
addRemoveLinks: true,
init: function() {
dzClosure = this;
document.getElementById("submit-all").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("fname", jQuery("#fname").val());
formData.append("lname", jQuery("#lname").val());
});
}
}
});
});
submit.php
<?php
require_once "db.php";
$target_dir = "uploads/";
echo '<pre>';
if (move_uploaded_file($_FILES["file"]["tmp_name"][0], $target_dir.$_FILES['file']['name'][0])) {
$status = 1;
echo 'uploaded, ';
}
else {
echo 'not uploaded, ';
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
if(mysqli_query($conn, "INSERT INTO CF_form(fname, lname
) VALUES('" . $fname . "', '" . $lname . "')")) {
echo 'sent';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
As I said, this all works on my local host but on the live site the file doesn't appear. I get the 'sent' message and the debugging info is like this:
uploaded, Here is some more debugging info:
Array
(
[file] => Array
(
[name] => Array
(
[0] => IMG_1129.JPG
)
[type] => Array
(
[0] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpriOyPQ
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 2181000
)
)
)
sent
The uploads directory is set to 777. Just can't figure out why I'm not getting the files.
I m sending html < p >hello< /p>
<div class="input-field">
<input id="price" type="number" ng-model="productData.price" ng-init="productData.price = ''" >
<label for="price">Price</label>
</div>
<div id="editor3" class="ql-container ql-snow">
<div class="ql-editor" data-gramm="false" contenteditable="true">
<p>hello</p>
</div>
</div>
<input type="hidden" ng-model="productData.description">
to angular js code, But it is not working. I am new to angular js. the fifth line below I thing not taking data from HTML code
$scope.addProdcut = function (productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": productData,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}
Controller file
public function addProduct()
{
if ($this->request->is('post')) {
$content = $this->request->input('json_decode', true);
$data = $content['data'];
$file = '';
if ($content['image'] != '') {
$file = date('ymd') . time() . '.' . 'jpg';
$path = WWW_ROOT . 'img/products/' . $file;
$this->base64_to_jpeg($content['image'], $path);
}
$products = TableRegistry::get('Products');
$query = $products->query()->insert(['item', 'price', 'description', 'image', 'status', 'added_by', 'created'])
->values([
'item' => $data['name'],
'price' => $data['price'],
'description' => $data['description'],
'image' => $file,
'status' => 1,
'added_by' => $this->loggedInUser['id'] . '||' . $this->loggedInUser['username'],
'created' => date("Y-m-d\TH:i:s"),
])->execute();
echo json_encode(['status' => 'success']);
exit;
}
}
it is a word editor in form, from where I want to save HTML code (from word editor) in data base using a hidden input field. by sending data ng-model to that hidden input field
You are storing the value in $scope.productData.description and then sending productData, instead, you should send $scope.productData.description.
$scope.addProdcut = function(productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": $scope.productData.description,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}
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;
}