How to install vue-laravel-image-crop-upload in laravel? - ajax

I need use vue-laravel-image-crop-upload in Laravel 8.
First step:
Add js script file in my project:
https://dai-siki.github.io/vue-image-crop-upload/example/demo-src.js
Then use this code in html:
<div id="app">
<div class="item">
<img v-if="avatarUrl2" v-show="true" class="avatar" :src="avatarUrl2" style="" />
<my-upload
key="0"
url="/club/uploadCover"
field="avatar2"
lang-type="ar"
:value.sync="show2"
:params="otherParams"
></my-upload>
</div>
<button class="release__buy btn-cover" #click="toggleShow2">Select</button>
</div>
After click select button and select image, Show 419 unknown status.
How to set CSRF token in ajax?

One way is to pass param
#php
$data=['_token'=>csrf_token()];
#endphp
and in vuejs component
<my-upload url="{{route("test")}}" img-format="jpg" img-bgc="#fff"
:lang-ext="{hint: '点击,或拖动图片至此处(*^_^*)'}"
v-model="show1"
field="avatar1"
ki="0"
#crop-success="cropSuccess"
#crop-upload-success="cropUploadSuccess"
#crop-upload-fail="cropUploadFail"
:no-rotate="false"
:params="{{json_encode($data)}}"></my-upload>
Also use core package
Ref:https://github.com/dai-siki/vue-image-crop-upload
You are using fork package(https://github.com/ibohonos/vue-laravel-image-crop-upload) which is not updated one
Also you can route url too like url="{{route("test")}}"
Scripts i used from original package
<script src="https://dai-siki.github.io/vue-image-crop-upload/example-2/vue.js"></script>
<script src="https://dai-siki.github.io/vue-image-crop-upload/example-2/demo-src.js"></script>
If you want to pass using headers then
#php
$data=['X-CSRF-TOKEN'=>csrf_token()];
#endphp
then in component
<div class="item">
<a class="btn" #click="toggleShow2">Set Avatar</a>
<img class="avatar" v-if="avatarUrl2" :src="avatarUrl2" v-show="true" style="display: none;">
<my-upload url="{{route("test")}}"
#crop-success="cropSuccess"
#crop-upload-success="cropUploadSuccess"
#crop-upload-fail="cropUploadFail"
:no-square="true"
field="avatar2"
ki="0"
lang-type="en"
v-model="show2"
:headers="{{json_encode($data)}}"
></my-upload>
</div>

You have to use node package manager or npm to install module
use this command npm install vue-image-crop-upload
Visit Docs

Try
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
as referenced here https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token

Related

Laravel Breeze Vue - Link and page not rendering

I working on an app and using Laravel Breeze Vue for the first time. Just some quick background, Laravel Breeze provides some quick scaffolding for authentication. When a user logs in, they are presented with a simple dashboard page. I have added a new link to this page as per below.
app/resources/js/Layouts/Authenticated.vue
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
<BreezeNavLink :href="route('dashboard')" :active="route().current('dashboard')">
Dashboard
</BreezeNavLink>
<BreezeNavLink :href="route('client.index')" :active="route().current('client.index')">
Clients
</BreezeNavLink>
</div>
I have also created an Index.vue file at file path app/resources/js/Pages/Client/Index.vue. It looks like below:
<template>
<Head title="Clients" />
<BreezeAuthenticatedLayout>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Clients
</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
You're logged in!
</div>
</div>
</div>
</div>
</BreezeAuthenticatedLayout>
</template>
<script>
import BreezeAuthenticatedLayout from '#/Layouts/Authenticated.vue'
import { Head } from '#inertiajs/inertia-vue3';
export default {
components: {
BreezeAuthenticatedLayout,
Head,
},
}
</script>
I am using a route resource in my web.php file as per below. I have confirmed that client.index is an existing route via php artisan route:list.
//client routing
Route::middleware(['auth', 'verified'])->group(function() {
Route::resource('client', ClientController::class);
});
I am facing two problems. The first problem is that the link will not render in my navigation links. The second issue is that the Index.vue page will not render as well. I have tried doing npm run dev, npm run watch and clearing caches. None of these have worked. Please provide me with some insight on how to address these issues.
This is closed. I'm using old hardware and it was taking time to pick up the changes. npm run dev performed as expected.

Autosave content of TinyMce editor on change event (with laravel 7)?

I want to autosave the content of tinyMce editor
I'm using tinmce version 5.2.2 with laravel V7
tinymce configuration in app.js
require('./bootstrap');
require('tinymce/themes/silver');
require('tinymce/plugins/image');
require('tinymce/plugins/code');
require('tinymce/plugins/save');
import tinymce from 'tinymce';
tinymce.init({
selector:'textarea#inputQuestionTitle',
height:400,
setup: function(editor) {
editor.on('Change Keyup', function () {
editor.save();
//tinyMCE.triggerSave() <-- also tried
});
}
With following View
#extends('dashboard.layout')
#section('content')
<form id='addQ' action="{{route('questions.store')}}" method="post" enctype="multipart/form-data" >
#csrf
<div class="form-row align-items-center " >
<div class="col-md-12">
<label class="sr-only" for="inputQuestionTitle">Title</label>
<textarea name="title" class="form-control mb-2 " id="inputQuestionTitle" placeholder="Question Title"> </textarea>
</div>
</div>
<div class="form-row">
<button type="submit" class="btn btn-primary mb-2">Add new category </button>
</div>
</form>
<script type="text/javascript" src="{{asset('js/app.js')}}"></script>
<script type="text/javascript">
$(function(){
$('#addQ').submit(function(e){
e.preventDefault();
var frmdata = $(this).serialize();
console.log(frmdata);
});
});
</script>
#endsection
Outputs
I had using jquery to show input request with console.log
As showed in output title field does not returns any value
Please tell me how i autosave the content of tinymce editor and send it with input request ..
I had also tried to tinymce.triggerSave() before serialize() method of ajax so that input request will take tinymce content but not works
Instead of trying to update the textarea via the triggerSave() or save() methods while someone is editing the content I would just place tinymce.triggerSave() at the very beginning of the function that submits the page. This will ensure that the triggerSave() is called directly before you grab the content from the textarea.

Ember : if a value is set in controller , perform an Ajax command(written in template),

I have given a rough code to understand what I need to perform,
/app/route1/controller.js
export default Controller.extend({
test: function(id) {
$.ajax({
.....
.....
.....
}).then(() => {
set('message','successfully added');
});
}
});
/app/route1/template.hbs
<div class="ui container">
<div class="ui segment"
<button class="ui button" {{action "test" model.id}}>Submit</button>
</div>
</div>
<div class="ui container">
<div class="ui modal">
<div class="header"
Message
</div>
<div class="content"
{{message}}
</div>
<div class="actions">
<div class="ui ok button">OK</button>
</div>
</div>
</div>
<script type="text/javascript">
$.ajax({
if(message) {
$('.ui.modal').modal('show');
}
})
</script>
If I set a message in controller then, I have to show this message in the MODAL. The Ajax command that I've written is not correct., Please help to solve this issue.
Thanks in advance
First, you must not use <script> tags with ember. This won't work as expected and is in no way supported.
If you have to manually access DOM you should use the didInsertElement of a component.
Are you absolutly sure you want to build your modal yourself? There are many addons providing a nice API for modals. If you can use one of them. If you cant you basically have to write your own modal component.
I will not instruct your in detail how to do this, because this seems not to be your primary question.
Now about your test function. first you seem to try to use it as an action:
{{action "test" model.id}}
however for this you must place the function under the actions hash.
Next this line is wrong:
set('message','successfully added');
you either must use this.set('message','successfully added'); or set(this, 'message','successfully added');
Then you can display your message like this:
{{#if message}}
{{#modal-dialog
onClose=(action (mut isShowingBasic) false)
}}
{{message}}
{{/modal-dialog}}
{{/if}}
And it will work as expected.

WebAPI Knockout JS Image Binding

I am using Knockoutjs to render a user profile page. For which I am calling a Web API service which returns User details with its Profile Picture.
var MessageFrom = {
FromUserProfileId: self.FromUserProfileId,
FromUserName: self.FromUserName,
FromUserPictURL: self.FromUserPictURL
}
<div id="comments" class="comments" data-bind="with: viewModel">
<div class="comment clearfix" data-bind="foreach: Messages">
<div class="comment-avatar">
<img class="img-circle" data-bind="attr:{'src': FromUserPictURL}" alt="avatar">
</div>
<header>
<h3 data-bind="text: FromUserName"></h3>
<div class="comment-meta"><p data-bind="text: moment(DatePosted).format('LLL')"></p> </div>
</header>
<div class="comment-content">
<div class="comment-body clearfix">
<p data-bind="text: MessageBody"></p>
</div>
</div>
</div>
</div>
The URL of the Image returned from WebAPI is Relative URL like ~/Content/Member/Image1.jpg. While its bind with Image URL shows like "http://sitename.com/profile/~/Content/Member/Image1.jpg".
Everything works great accept Profile Picture
I need to work something on binding as as I cannot change the Path coming from Database.
Appreciate your suggestions.
Regards,
Your binding looks okay. For starters I would use your IE or Chrome developer tools ( F12 ) and change the src manually of the image to find out what exactly works for you.
You say you recieve this: ~/Content/Member/Image1.jpg
Setting the src to this should work: /Content/Member/Image1.jpg
You can change your message object client-side like this, once you're sure what is needed, but I think this should suffice:
var MessageFrom = {
FromUserProfileId: self.FromUserProfileId,
FromUserName: self.FromUserName,
FromUserPictURL: self.FromUserPictURL.replace('~','')
}

Refresh g:each tag via AJAX call in Grails

I have a statistical panel which displays the last registered users. I want to implement a AJAX call to upload the panel without having to reload the full page.
I have the following code in my view:
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
<div class="mt-comment">
<div class="mt-comment-img">
<g:if test="${user?.avatar}">
<img src="${createLink(controller:'controllerUser',
action:'image', id: user?.id)}" />
</g:if>
<g:else>
<img class="img-circle"
src="${resource(dir: 'img/profile', file: 'user_profile.png')}"/>
</g:else>
</div>
<div class="mt-comment-body">
<div class="mt-comment-info">
<span class="mt-comment-author">${user?.username}</span>
<span class="mt-comment-date">
<g:formatDate date="${user?.dateCreated}"/>
</span>
</div>
<div class="mt-comment-text">${user?.email}</div>
<div class="mt-comment-details">
<g:if test="${user?.enabled}">
<span class="mt-comment-status label label-sm label-success circle">
</g:if>
<g:else>
<span class="mt-comment-status label label-sm label-info circle">
</g:else>
<g:formatBoolean boolean="${user?.enabled}"/>
</span>
<ul class="mt-comment-actions">
<li>
<g:link controller="user" action="edit" id="${user?.id}">Edit</g:link>
</li>
</ul>
</div>
</div>
</div>
</div>
</g:each>
Also, I have a button when it is clicked calls the AJAX function. The Ajax function receives the data successful in JSON format. From there, I don't know upload my g:each tag.
I have tried the remoteFunction of Grails to use the upload attribute, but an error appears: No javascript provider is configured and I have searched the solution but anything works me.
The AJAX call:
$('.button').click(function() {
$.ajax({
url: URL,
success: function(data) {
console.log(data[index]);
console.log(val.username);
console.log(val.dateCreated);
console.log(val.email);
console.log(val.enabled);
console.log(val.avatar);
console.log(val.id);
},
error: function(){
},
});
Thanks for helping me.
Instead of Using JSON Data, You can do this using grails templates and jQuery load method. Here is a quick POC.
Template (_userComments.gsp)
This will act as a reusable view which can be called via AJAX or can be included directly in other views.
<g:each in="${lastUsers}" var="user">
<div class="mt-comments">
.....
</div>
</g:each>
View (main.gsp)
Our Main View.
<div class="userComments">
<!-- When the Page is Loaded, We need render this without an Ajax Call -->
<g:render template="userComments" model="['lastUsers':lastUsers]"/>
</div>
Javascript
$('.button').click(function() {
$( ".userComments" ).load( "user/userComments" );
});
Controller
We are defining two methods one for the main view and one for the ajax call.
def index() {
def lastUsers = User.list();
render(view:'main', model: [lastUsers: lastUsers])
}
// Ajax Call
def userComments() {
def lastUsers = User.list(); // what ever your fetch logic is
render(template:'userComments', model: [lastUsers: lastUsers])
}

Resources