Sending image to controller with javascript - javascript

I want to send image to controller with Javascript httpostedfile is null, how can I do this?
HTML
<input type="file" id="input-filee" name="sliderResimUrl" accept=".jpg" onchange="handleChange2()" hidden />
Javascript
function sliderGuncelle(th) {
getValue("/B2BAdmin/SliderDuzenle",
{ id: ID, SliderBolge: $("#SliderBolge").val(), SliderAd: $("#sliderAd").val()},
function (data, err) {
if (data =="Basarili") {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Güncelleme İşlemi Başarılı ! '
})
setInterval(function () {
window.location.reload(false);
}, 1000);
}
})
}
I tried to send the values ​​using javascript using the official form here, but I couldn't get it to work.
Controller
public ActionResult SliderDuzenle(int id,string SliderAd,int SliderBolge,HttpPostedFileBase sliderResimUrl)
{
using (BIRLIKB2BEntities db = new BIRLIKB2BEntities())
{
var deger = db.Slider.Where(x => x.ID == id).FirstOrDefault();
deger.SliderAd = SliderAd;
deger.SliderBolge = SliderBolge;
db.SaveChanges();
return Json("Basarili");
}
}

Related

Laravel: Redirect with flash message after submitted form using vue.js

I have two components: Index and Create. Both of these components are loaded from different blade files. The problem is I cannot pass flash message as a prop since these are in different files. How to redirect after a submitted form has been created and and receive the flash message in component Index from Create?
public function store(Request $request)
{
Service::create([
'name' => $request->get('name'),
'vendor_id' => $request->get('vendor'),
'desc' => $request->get('desc'),
'hours' => $request->get('hours'),
'price_per_hour' => $request->get('price'),
'fixed_price' => $request->get('fixed_price'),
'user_id' => $request->user()->id
]);
if (\request()->wantsJson()) {
return response()->json([
'alert_store' => 'New service added successfully.'
]);
}
}
Create component:
if(ok) {
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/api/services', {
name: this.form.name,
vendor: this.form.vendor,
desc: this.form.desc,
hours: this.form.hours,
price: this.form.price,
fixed_price: this.form.fixed_price,
})
.then(response => {
this.alert_store = response.data.alert_store
alert(this.alert_store)
window.location.href = '/admin/services';
})
.catch(function (error) {
console.log(error);
});
});
}
},
index.vue:
import Create from './Create.vue';
import Alert from '../Alert.vue';
export default {
props: ['alert_store'],
components: {
Create,
Alert,
},
data(){
return {
services: [],
alert_success: '',
alert_error: '',
errors: [],
success: [],
form: {
name: '',
desc: '',
hours: '',
price_per_hour: '',
vendor: '',
fixed_price: '',
},
selected: null,
}
},
mounted() {
this.loadServices()
this.getStatus()
},
methods: {
loadServices: function(){
axios.get('/api/getservicedata')
.then(response => {
this.services = response.data;
})
.catch(function(error){
console.log(error);
});
},
// getStatus(){
// axios
// .post('/api/services')
// .then(response => {
// console.log(response.data.alert_store)
// });
// },
isEditable(service)
{
this.form.name = service.name
this.form.desc = service.desc
this.form.hours = service.hours
this.form.price_per_hour = service.price_per_hour
this.form.vendor = service.vendor.id
this.form.fixed_price = service.fixed_price
if(service.isEditing)
{
this.selected = service.id
service.isEditable = false
}
this.$set(service, 'isEditing', true)
},
editService(service)
{
if(confirm('Are you sure?'))
{
axios.post(`/api/services/${service.id}`, {
_method: 'patch',
name: this.form.name,
vendor: this.form.vendor,
desc: this.form.desc,
hours: this.form.hours,
price_per_hour: this.form.price_per_hour,
vendor: this.form.vendor,
fixed_price: this.form.fixed_price
})
.then(response => {
this.alert_success = response.data.alert_update
this.success.push(Alert)
this.loadServices()
})
.catch(response => {
this.errors.push(Alert)
this.alert_error = `Could not edit, ${service.name}, from services!`
})
}
},
deleteService(service)
{
if(confirm('Are you sure?'))
{
axios.get('/sanctum/csrf-cookie').then(response => {
axios.delete(`/api/services/${service.id}`, {
__method: 'DELETE'
})
.then(response => {
this.alert_success = response.data.alert_delete
this.success.push(Alert)
this.loadServices()
})
.catch(response => {
this.errors.push(Alert)
this.alert_error = `Could not delete, ${service.name}, from services!`
})
});
}
}
}
}
You could pass props into index.vue component with different ways.
First and properly (on my mind) way is to use session data.
Like:
public function store(Request $request)
{
Service::create([
'name' => $request->get('name'),
'vendor_id' => $request->get('vendor'),
'desc' => $request->get('desc'),
'hours' => $request->get('hours'),
'price_per_hour' => $request->get('price'),
'fixed_price' => $request->get('fixed_price'),
'user_id' => $request->user()->id
]);
\request()->session()->put('yourawesomekey','value');
if (\request()->wantsJson()) {
return response()->json([
'alert_store' => 'New service added successfully.'
]);
}
}
And when you initialize your component in blade file:
...
<your-component-name alert_store="{{ session('yourawesomekey', 'default-value') }}" />
...
NOTE Don't forgot to cleanup session data \request()->session()->forget('yourawesomekey');
Hope it will work for you.

function is not called upon submit

I created this form to submit some info to the server-side. The form is in HTML/CSS and I am using AngularJS latest version. I also made sure that the button is inside the form. I know its most common mistake. But still, it's not working. The function I want to call is "onAddEditTenantSubmitForm" which is also assigned to state as well. I have checked it using the Chrome browser and marked line number 87. but it does not trigger. Also there is no error in the console too.
Below is the link to JSFiddle
https://jsfiddle.net/jLtsuonx/
'''
(function () {
var app = angular.module('app');
app.controller('MultiTenantController', ['$scope', '$filter', 'TenantServices', function ($scope, $filter, TenantServices) {
var uibModal = null;
var test = "Multi Tenat Controller";
var state = {
tenantModel: {
addedOn: '',
connectionString: '',
createdBy: '',
endOn: '',
id: '',
identifier: '',
isDisabled: '',
items: [{
isDisabled: '',
tenantType: '',
}],
name: '',
startFrom: '',
tenantType: '',
userId: '',
},
};
var init = function () {
$(document).ready(function () {
tenantTable = $('#table_Tenants').DataTable({
ajax: {
url: 'API/MultiTenant/Pagged',
method: 'POST'
},
columns: [
{ data: 'name' },
{ data: 'identifier' },
{ data: 'connectionString' },
{
data: 'startFrom',
render: function (startFrom) {
return $filter('date')(startFrom, 'medium');
}
},
{
data: 'addedOn',
render: function (addedOn) {
return $filter('date')(addedOn, 'medium');
}
},
{
data: 'endOn',
render: function (endOn) {
return $filter('date')(endOn, 'medium');
}
},
{
data: 'actions',
orderable: false,
render: function () {
return `<div class="list-icons">
<div class="dropdown">
<a href="#" class="list-icons-item" data-toggle="dropdown">
<i class="icon-menu9"></i>
</a>
<div class="dropdown-menu dropdown-menu-right">
<i class="icon-database-edit2"></i>Edit
<i class="icon-database-remove"></i>Delete
</div>
</div>
</div>`;
}
}
]
});
tenantTable.on('click', '.deleteTenant', function () {
const $row = $(this).closest('tr');
const rowData = tenantTable.row($row).data();
deleteTenant(rowData);
});
})
};
const onAddEditTenantSubmitForm = function (newTenatForm) {
if (!state.tenantModel.userId) {
addTenant(newTenatForm);
}
else {
//updateUser(newUserForm);
}
};
var addTenant = function (newTenatForm) {
state.isLoading = true;
TenantServices.addTenant(state.tenantModel).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant has been created',
type: 'success'
});
userTable.ajax.reload();
closeModal();
},
function (errorResponse) {
if (errorResponse.status === 400 && errorResponse.data.duplicateRecord) {
}
else if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while adding tenant.',
type: 'error'
});
}
}
)
.finally(() => state.isLoading = false);
};
var deleteTenant = function (rowObj) {
state.isLoading = true;
TenantServices.deleteTenant(rowObj.id).then(
function () {
swalInit.fire({
title: 'Success',
text: 'Tenant Deleted!',
type: 'success'
});
tenantTable.ajax.reload();
closeModal();
},
function (errorResponse) {
if (errorResponse.status === 500) {
swalInit.fire({
title: 'Server Error',
text: 'An server error occurred while Deleting Tenant.',
type: 'error'
});
}
else if (errorResponse.status === 404) {
swalInit.fire({
title: 'Server Error',
text: 'Tenant not found on Server.',
type: 'error'
});
}
}
)
.finally(() => state.isLoading = false);
};
var closeModal = function () {
if (uibModal) {
uibModal.close();
}
};
state.onAddEditTenantSubmitForm = onAddEditTenantSubmitForm;
state.test = test;
$scope.state = state;
$scope.init = init;
}]);
})();
'''
You need the function you are calling on the template via ng-submit to be in your scope and then change the template to call it correctly.
On your controller update your function from a const and tie it to scope
$scope.onAddEditTenantSubmitForm = function (newTenatForm) {
On your template add "$ctrl." as a prefix to your function
ng-submit="$ctrl.onAddEditTenantSubmitForm(newTenatForm)"

Hosted fields in braintree gives error "Cannot determine payment method" PHP Laravel

Can anyone please explain me how could i make a working Braintree payment with hosted fields, in Laravel. I tried to look at the documentation myself but i couldn't make it working.
i created the token in the controller to be sent to the view like:
$gateway = new \Braintree\Gateway([
'environment' => config('services.braintree.environment'),
'merchantId' => config('services.braintree.merchantId'),
'publicKey' => config('services.braintree.publicKey'),
'privateKey' => config('services.braintree.privateKey')
]);
$paypalToken = $gateway->ClientToken()->generate();
return view('checkout')->with(['paypalToken' => $paypalToken]);
On the blade view i have this JS:
var form = document.querySelector('#payment-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: '{{ $paypalToken }}'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
// submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload){
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
}, false);
});
// Create a PayPal Checkout component.
braintree.paypalCheckout.create({
client: clientInstance
}, function (paypalCheckoutErr, paypalCheckoutInstance) {
if (paypalCheckoutErr) {
console.error('Error creating PayPal Checkout:', paypalCheckoutErr);
return;
}
// Set up PayPal with the checkout.js library
paypal.Button.render({
env: 'sandbox', // or 'production'
commit: true,
payment: function () {
return paypalCheckoutInstance.createPayment({
flow: 'checkout', // Required
amount: '{{ presentPrice($newTotal + 5000) }}', // Required
currency: 'USD', // Required
});
},
onAuthorize: function (data, actions) {
return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
// Submit `payload.nonce` to your server.
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
},
onCancel: function (data) {
console.log('checkout.js payment cancelled', JSON.stringify(data, 0, 2));
},
onError: function (err) {
console.error('checkout.js error', err);
}
}, '#paypal-button').then(function () {
// The PayPal button will be rendered in an html element with the id
// `paypal-button`. This function will be called when the PayPal button
// is set up and ready to be used.
});
});
});
Here is the method in were i process the payment:
$gateway = new \Braintree\Gateway([
'environment' => config('services.braintree.environment'),
'merchantId' => config('services.braintree.merchantId'),
'publicKey' => config('services.braintree.publicKey'),
'privateKey' => config('services.braintree.privateKey')
]);
$nonce = $request->payment_method_nonce;
$result = $gateway->transaction()->sale([
'amount' => round(getNumbers()->get('newTotal') / 100, 2),
'paymentMethodNonce' => $nonce,
'options' => [
'submitForSettlement' => True
]
]);
if ($result->success) {
$transaction = $result->transaction;
$order = $this->addToOrdersTablesPaypal(
$email,
$firstName.' '.$lastName,
null
);
return redirect()->route('confirmation.index')->with('success_message', 'Thank you! Your payment has been successfully accepted!');
} else {
$order = $this->addToOrdersTablesPaypal(
$email,
$firstName.' '.$firstName,
$result->message
);
return back()->withErrors('An error occurred with the message: '.$result->message);
}
can anyone help me, understand what is missing?
i solved it, i actually found an workaround, i had to create a controller for the hosted fields, and it worked.

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'id' of undefined" in VueJS and Laravel

I have a table with the ability to add new items and edit existing ones (with the edit button being next to each entry). I have an issue with it whereby if you were to add a new item, NOT refresh the page, but then go to edit the item, it will edit it on Vue but not pass the edit back to the database. When you go to edit an item, the PUT URL returns a 404 error. If however, you refresh the page after adding an item, you can edit it perfectly fine. Any ideas what I've done wrong, or maybe forgotten to add? Same for the delete method too.
<script>
export default {
data: () => ({
dialog: false,
headers: [
{
text: 'Question',
align: 'left',
sortable: true,
value: 'question',
width: '25%'
},
{ text: 'Answer', value: 'answer', width: '55%' },
{ text: 'Actions', value: 'action', sortable: false, width: '20%' },
],
questions: [],
editedIndex: -1,
editedItem: {
question: '',
answer: ''
},
defaultItem: {
question: '',
answer: ''
},
}),
computed: {
formTitle () {
return this.editedIndex === -1 ? 'New Item' : 'Edit Item'
},
},
watch: {
dialog (val) {
val || this.close()
},
},
created () {
this.initialize();
this.loadUsers();
},
methods: {
initialize () {
this.questions = []
},
loadUsers(){
if (axios == null) {
return;
}
axios.get('/api/faq').then(res=>{
if(res.status === 200){
this.questions=res.data;
}
}).catch(err=>{
console.log(err);
});
},
editItem (item) {
this.editedIndex = this.questions.indexOf(item);
this.editedItem = Object.assign({}, item);
this.dialog = true
},
deleteItem (item) {
const index = this.questions.indexOf(item);
confirm('Are you sure you want to delete this item?') &&
axios.destroy('/api/faq/' + this.questions[this.editedIndex].id).then(response =>{
this.questions.splice(index, 1);
}).catch(error=>{
console.log('Deleting error')
})
},
close () {
this.dialog = false;
setTimeout(() => {
this.editedItem = Object.assign({}, this.defaultItem);
this.editedIndex = -1
}, 300)
},
saveToServer () {
if (this.editedIndex > -1) {
// Edit item
Object.assign(this.questions[this.editedIndex], this.editedItem);
axios.put('/api/faq/' + this.questions[this.editedIndex].id, this.editedItem).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
} else {
//New item
this.questions.push(this.editedItem);
axios.post('/api/faq', this.editedItem).then(function (response) {
console.log('Before');
this.id = response.id;
console.log('After');
Object.assign(this.questions[this.editedIndex], this);
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
this.close()
},
},
}
</script>
Store Controller:
public function store(Request $request)
{
$id = faq::insertGetId($request->all());
return Response:: json([
'status' => 'ok',
'id' => $id,
], 200);
}
Update Controller:
public function update(Request $request, $id)
{
faq::findOrFail($id)->update($request->all());
return response(['message' => 'Success']);
}

Remove class for another user vue.js

I have chat message system.
I have code:
<template>
<li :class="className">
{{ message }}
</li>
</template>
<script>
export default {
props: [
'message',
'user',
'time',
'seen',
],
computed: {
className() {
return this.seen;
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
App.js:
data:{
message: '',
convId: 1,
chat: {
message: [],
user: [],
time: [],
seen: [],
},
typing: '',
},
....
watch: {
message() {
Echo.private('chat')
.whisper('typing', {
name: this.message
});
}
},
methods: {
send(){
if(this.message.length != 0 && this.message.length <= 4000) {
this.chat.message.push(this.message);
this.chat.user.push('you');
this.chat.time.push(this.getTime());
this.chat.seen.push('unread'). //set class unread message for user
axios.post('/sendMessage', {
message: this.message,
//lastName: 'Flintstone'
})
.then(response => {
console.log(response);
this.message = '';
})
.catch(error => {
console.log(error);
});
}
},
seenMessage() {
axios.post('/setMessagesSeen/' + this.convId) //this request mark messages in chat all readed for auhenticated user
.then( response => { this.chat.seen.push(''); //remove unread class })
.catch( response => { console.log(response) } )
},
getTime() {
let time = new Date();
return time.getHours() + ':' + time.getMinutes();
}
},
mounted() {
Echo.private('chat')
.listen('ChatEvent', (e) => {
this.chat.message.push(e.message);
this.chat.user.push(e.user);
this.chat.time.push(this.getTime());
this.chat.seen.push('unread'). //set class unread message for user
console.log(e);
})
.listenForWhisper('typing', (e) => {
if(e.name != '')
this.typing = 'typing..';
else
this.typing = null;
});
}
My chat.blade.php:
<message v-for="value,index in chat.message"
:key=value.index
:user=chat.user[index]
:message="chat.message[index]"
:time="chat.time[index]"
:seen="chat.seen[index]"
>
</message>
<div class="form-group">
<textarea maxlength="4000" cols="80" rows="3" class="message-input form-control" v-model='message' v-on:click="seenMessage"></textarea>
</div>
<div class="form-group">
<button type="button" class="btn btn-lg btn-primary" v-on:click="send">Send message</button>
</div>
My function seen:
public function setMessagesSeen(Conversation $conversation) {
$user = User::find(Auth::id());
$conversations = Chat::conversation($conversation->id);
//$dd = Chat::conversations($conversation)->for($user)->readAll();
dd(Chat::conversations($conversations)->for($user)->getMessages()->where('body', 'asdfsadfsd'));
//$message = Chat::messages($message)->for($user)->markRead();
broadcast(new HasSeenMessage($message));
return response('ok');
}
How I can send class "unread" to element div other user? I can paste class on current user, and I get color on element chat only for me, but how I can hide element for me and other user, when message is seen?
I want do read/unread function for users.
Example:
If user in real time send message I send class unread, when other user click on textarea, I remove class unread, and said user, that message is seen. How I can do it in real time add/remove class unread? My function is not working.
To do this you have to create an Event in your Laravel application that you will broadcast on a precise channel (you can for example give the name 'chat. {Conversation}. {User_id}') and with Laravel Echo you will listen this event!
I allowed myself to make some changes in your code -:)
I presume you have this class HasSeenEvent
<?php
namespace App\Events;
use App\Order;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class HasSeenEvent implements ShouldBroadcast
{
use SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #param Message $message
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
public function broadcastOn()
{
// I presume we can get conversation id like this : $this->message->conversation->id
return new PrivateChannel('chat.'.$this->message->conversation->id.'.'.$this->message->sender->id);
}
}
Then, in your routes/broadcast.php declare this route chat.{conversation}.{user_id}
In the function where you put the 'seen' to 1 you broadcast the event at the same time
broadcast(new HasSeenMessage($message))
Then you listen to this event in your vuejs code
components/Message.js
<template>
<li :class="className">
{{ message }}
</li>
</template>
<script>
export default {
props: [
'message',
'user',
'time',
'readed',
],
computed: {
className() {
return this.readed == 1 ? 'seen' : 'unread';
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
chat.blade.php
<message v-for="message,index in chat.messages"
:key="index"
:user="message.user"
:message="message.content"
:time="message.time"
:readed="message.readed"
>
</message>
<div class="form-group">
<button type="button" class="btn btn-lg btn-primary" v-on:click="send">Send message</button>
</div>
App.js
data: {
message: '',
convId: 1,
chat: {
messages: [],
/* message: [],
user: [],
time: [],
seen: [], */
},
typing: '',
},
....
watch: {
message() {
Echo.private('chat')
.whisper('typing', {
name: this.message
});
}
},
methods: {
send() {
if (this.message.length != 0 && this.message.length <= 4000) {
let data = {
content: this.message,
user: 'you',
time:this.getTime(),
readed: 0
}
this.chat.messages.push(data)
data = {}
axios.post('/sendMessage', {
message: this.message,
//lastName: 'Flintstone'
})
.then(response => {
console.log(response);
this.message = '';
})
.catch(error => {
console.log(error);
});
}
},
seenMessage() {
axios.post('/setMessagesSeen/' + this.convId) //this request mark messages in chat all readed for auhenticated user
.then(response => {
//This is not the best way to do that
this.chat.messages[this.messages.length -1 ].readed = 0
}).catch(response => {
console.log(response)
})
},
getTime() {
let time = new Date();
return time.getHours() + ':' + time.getMinutes();
}
},
mounted() {
Echo.private('chat')
.listen('ChatEvent', (e) => {
this.chat.messages.push({
content: e.message,
user: e.user,
time: this.getTime(),
readed: 0
})
console.log(e);
})
.listenForWhisper('typing', (e) => {
if (e.name != '')
this.typing = 'typing..';
else
this.typing = null;
});
// I presume to can access to user info
let that = this
Echo.private('chat.'+convId+'.'+user.id)
.listen('HasSeenMessage', (e) => {
let message = e.message
let lookingForMessage = that.chat.messages.find((m) => {
// I presume in your db messages table has field content and time
return m.content == message.content && m.time => message.time
})
try {
lookingForMessage.readed = 1
}catch (err){
// message not found
console.log(err)
}
})
}
Hope it helped you!

Categories