Laravel : Axios not saving the data in edit page - php

I create an edit page to edit the data. After the user edits the form. The form should be saved. But in my case I can't save the form it's showing error.
I facing this error.
ReminderComponent.vue
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import MarkdownIt from 'markdown-it'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
var msg_editor;
Vue.use(VueAxios, axios);
const md = new MarkdownIt({
linkify: true
})
export default {
props: ['email_creation_link', 'email_index_route', 'email_edit_route','conditions','modules','mailtemplates'],
components: {
},
data() {
return {
template:
{
subject: '',
message: '' ,
days: '',
condition_id: 1,
},
options:[
{
display:'Client Name',
actual:'Client name'
},
{
display:'Joined Date',
actual:'Joined date'
},
{
display:'Module Name',
actual:'Module name'
},
{
display:'Last Seen',
actual:'Last seen'
},
],
showName: false,
}
},
mounted(){
var self = this;
ClassicEditor
.create(document.querySelector( "#msg"),
{
})
.then(editor => {
msg_editor = editor;
editor.model.document.on( 'change:data', () => {
self.template.message = msg_editor.getData();
});
})
.catch(error => {
console.error(error);
})
if (this.mailtemplates) {
this.template=this.mailtemplates;
}
},
methods: {
//Drag items
dragstart: function(item, e){
this.draggingItem = item;
e.dataTransfer.setData('text/plain', item.actual);
},
dragend: function(item,e) {
e.target.style.opacity = 1;
},
dragenter: function(item, e) {
this.draggingItem = item;
},
//content
replaceVariables(input)
{
let updated = input
return updated
},
//hidecontent
showHide: function(e)
{
console.log("Show "+e.target.value+ " fields")
this.showName = e.target.value !== ''
},
fetch()
{
//request data
axios.get(this.email_index_route,this.template)
.then((res) => {
this.template = res.data.template;
})
**axios.get(this.email_edit_route,this.mailtemplates)
.then((res) => {
this.mailtemplates = res.data.template;
})**
},
save()
{
//save data to db
axios.post(this.email_index_route, this.template)
.then((res) => {
alert('Mail sent successfull!')
})
**axios.post(this.email_edit_route, this.mailtemplates)
.then((res) => {
alert('Mail sent successfull!')
})**
},
addToMail: function(type, text)
{
if (type == 'message') {
this.template.message += text;
msg_editor.setData(this.template.message);
}
},
//user name replace
replaceVariables() {
return this.replaceVariables(this.options || '')
},
}
}
</script>
I think this area causing problem but i can't find the solution.
axios.get(this.email_edit_route,this.mailtemplates)
.then((res) => {
this.mailtemplates = res.data.template;
})
axios.post(this.email_edit_route, this.mailtemplates)
.then((res) => {
alert('Mail sent successfull!')
})
route file
Route::get('api/email/create', ['as' => 'email.create', 'uses' => 'Havence\AutoMailController#create']);
Route::get('automail/mail', 'Havence\AutoMailController#mail');
Route::get('automail/index',['as'=>'email.index','uses' => 'Havence\AutoMailController#index']);
Route::post('automail/edit/{id}',['as'=>'email.edit','uses' => 'Havence\AutoMailController#edit']);
Route::get('automail/delete',['as'=>'email.delete','uses' => 'Havence\AutoMailController#destroy']);
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!

As per your error and your route file you are using POST method on your edit page but your edit method accepts only GET method that is why you are getting this error.
I'm getting this error

Related

Why can't Fullcalendar show my data using Laravel Eloquent and jquery?

I've been having trouble with Full Calendar. I already tried different approaches but to no avail. The json response doesn't shows up in the calendar.
View:
<div class="col-lg-12 col-md-12">
<div id="calendar">
</div>
</div>
Controller:
public function calendar(Request $request){
if($request->ajax()){
$data= Table::where('id',Auth::user()->id)
->where('DateFrom','>',$request->start)
->where('DateTo','<',$request->end)
->get();
return response()->json($data);
}
}
Route:
Route::get('/calendar', [CalendarController::class, 'calendar'])->name('calendar');
Script (mix):
$('#calendar').fullCalendar({
events: 'calendar',
eventColor: '#378006',
displayEventTime: true,
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
})
There are no errors, the data is also being fetched but the problem is the calendar can't render it. May I ask is there any problem with this? Do I need to actually create a partial view for this and then include it to another blade file?
The problem was that I was fetching a different type of date which doesn't match up with the dates from the Fullcalendar. So to show/highlight those dates I did this.
Controller:
public function calendar(Request $request){
if($request->ajax()){
$event= Table::where('id',Auth::user()->id)
->where('DateFrom','>',date('Y-m-d',$request->start)) //converts date
->where('DateTo','<',date('Y-m-d',$request->end)) //converts date
->get();
$data = [];
foreach($event as $row){
$data[] = [
'title' => $row->title,
'start' => date(DATE_ISO8601,strtotime($row->DateFrom)),
'end' => date(DATE_ISO8601,strtotime($row->DateTo))
];
}
return response()->json(collect($data));
}
return view('partials._calendar-details',compact('data'));
}
and then for my script:
$('#calendar').fullCalendar({
// events: 'calendar',
eventColor: '#378006',
displayEventTime: false,
eventSources: [
{
events: function(start, end, timezone, callback ){
$.ajax({
url: '/calendar',
type: 'GET',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
dataType: 'json',
success: function(res) {
var events = [];
for (var i = 0; i < res.length; i++){
console.log(res[0].title);
events.push({
title: res[0].title,
start: res[0].start,
end: res[0].end
});
}
callback(events);
},
});
},
color: 'darkblue', // an option!
textColor: 'white', // an option!
}
],
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
})

transaction issue from one card (Vue App) to other card (in Laravel App)

Please I have an error in my Laravel app when I clicked on send(to send money from one card to another card using MySQL database)
The app couldn't send the data:
Error message (Crl +i + shift):
xhr.js?b50d:177 GET http://localhost:8000/api/transaction/pubkey 401 (Unauthorized)
below my code of vue.js:
<script>
import { JSEncrypt } from 'jsencrypt'
export default {
data() {
return {
user: {},
card: {
code: null,
key: null,
amount: 0
},
from:{},
to:{},
amount: null,
pubKey:"",
error: false,
errorMessage: ''
}
},
mounted() {
this.getUser();
},
methods: {
getUser(){
this.$http.post('http://localhost:8000/api/auth/me',
{},
{
headers: {
'Authorization': `Bearer ${localStorage.getItem("access_token")}`
}
}).then(res => {
this.user = res.data;
})
},
test(){
this.$http.get('http://localhost:8000/api/auth/test',
{
headers: {
'Authorization': `Bearer ${localStorage.getItem("access_token")}`
}
})
},
addCard(){
this.$http.post('http://localhost:8000/api/card',
{},
{
headers: {
'Authorization': `Bearer ${localStorage.getItem("access_token")}`
}
}).then(response=>{
this.card = response.data;
});
},
sendMoney(){
this.error = false;
this.errorMessage = '';
this.validate();
if (this.error){
return;
}
this.$http.get('http://localhost:8000/api/transaction/pubkey',
{
headers: {
'Authorization': `Bearer ${localStorage.getItem("access_token")}`
}
}).then(res => {
this.pubKey = res.data;
if (!this.pubKey) return;
this.encryptData();
this.$http.post('http://localhost:8000/api/transaction/',
{
from: this.from,
to: this.to,
amount: this.amount
},
{
headers: {
'Authorization': `Bearer ${localStorage.getItem("access_token")}`
}
}).then(res => {
console.log('sent');
}).catch(err => {
this.errorMessage = err.response.data.error;
this.error = true;
})
})
},
validate(){
if (!this.from.code) {
this.error = true;
}
if (!this.from.key) {
this.error = true;
}
if (!this.to.code) {
this.error = true;
}
if (!this.to.key) {
this.error = true;
}
if (!this.amount || this.amount <= 0) {
this.error = true;
}
if (this.error){
this.errorMessage = "check fields";
}
},
encryptData(){
let encryptor = new JSEncrypt();
encryptor.setPublicKey(this.pubKey);
this.from.code = encryptor.encrypt(this.from.code);
this.from.key = encryptor.encrypt(this.from.key);
this.to.code = encryptor.encrypt(this.to.code);
this.to.key = encryptor.encrypt(this.to.key);
console.log(this.from, this.to);
// encryptor.setPrivateKey();
// console.log(encryptor.decrypt(secretWord));
},
getPubkey(){
}
},
}
</script>
my transaction function:
public function addTransaction(Request $request){
$user = $this->user;
$data = $this->decryptedData($request);
// Check if auth user have card
if ($user->card->code != $data['from']['code'] || $user->card->key != $data['from']['key']){
return response()->json(['error' => 'Its not your card'], 401);
}
if(!$this->checkIfcardExist($data['to'])){
return response()->json(['error' => 'Reciever card not found'], 401);
}
if($user->card->code == $data['to']['code'] && $user->card->key == $data['to']['key']){
return response()->json(['error' => 'Very smart ... -_-'], 401);
}
if($user->card->amount < $request['amount']){
return response()->json(['error' => "Your poor XD"], 401);
}
$transaction = [
'from_id' => $this->getCardId($data['from']),
'to_id' => $this->getCardId($data['to']),
// 'amount' => (float)$request['amount']
];
Transaction::create($transaction);
return $transaction;
}
I run my Laravel app via cmd: PHP artisan serve : http://127.0.0.1:8000
I run my xmapp for my SQL data base
I run my vue app via cmd: npm run serve : Local: http://localhost:8080/
I can add new user form vue app to the data base , but the only this not working is the transaction function
any idea for this issue?

Server-side processing with ajax source data

I tried to submit dynamic data to jscript and render the data using php from api url, but how can I pass the pagination number to the datable jscript and letting php to define the pageindex dynamically?
I tried to pass the value into the function, it will totally reload the ajax table for me and stay back at page number 1 instead of page number 2.
the api returns:
{
"data": [...],
"pageindex": 1,
"totalrecord": 708,
"totalpage": 71
}
My Form jquery:
$('.form-filter form').on('submit', function(e) {
e.preventDefault();
const start = $('.form-filter [name=start]').val();
const end = $('.form-filter [name=end]').val();
const type = $('.form-filter [name=type]').val();
const status = $('.form-filter [name=status]').val();
if (this.checkValidity() !== false) {
action_handle('fire_search');
var datetime = timezone(start, end);
paymentTable(datetime[0], datetime[1], type, status);
}
});
The datatable jscript:
function paymentTable(from, to, type, status) {
const paymentTable = $('#table').DataTable({
ajax: {
type : "POST",
url: "/api/somethinng/history",
data: {"start": from, "end": to, "type": type, "status": status},
dataSrc: function(json) {
if(json == "no data") {
return [];
} else {
return json.data;
}
}
},
responsive: {
details: {
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'ui display nowrap table-sm table-bordered'
})
}
},
processing: true,
serverSide: true,
deferRender: true,
destroy: true,
order: [[0,"desc"]],
}
});
paymentTable.draw();
}
My PHP function to get the data from api:
public function api_history() {
$raw = $this->balance_model->data_source([
'type' => 1,
'status' => 1,
'fromdate' => '2020-10-01',
'todate'=> '2020-10-05',
'pageindex' => 1,
'rowperpage' => 1000
]);
if( $raw['code'] == 1 && $raw['data'] != [] ):
asort($raw['data']);
$data = [];
foreach( $raw['data'] as $ph ):
$row = [];
$row[] = $ph['date'];
$row[] = $ph['id'];
$row[] = $ph['amount'];
$data[] = $row;
endforeach;
echo json_encode([
'data' => $data
'draw' => (int)$_POST['draw'],
'recordsTotal' => $raw['totalRecord'],
'recordsFiltered' => $raw['totalRecord']
]);
else:
echo json_encode(['no data']);
endif;
}

Cannot trigger data selected in vue-select when show record

I am using vue-select. I select province_id then create record success, but when show record, I cannot trigger data selected to select2.
<v-select
v-model="form.province_id"
name="province_id"
:options="provinces"
:reduce="province => province.province_id"
label="name"
:clearable="false"
:searchable="true" />
import vSelect from 'vue-select'
export default {
components: { 'v-select': vSelect },
data () {
const form = {
province_id: ''
}
return {
provinces: []
}
},
}```
Your data declaration is wrong, you need to return form inside the returned object.
import vSelect from 'vue-select'
export default {
components: { 'v-select': vSelect },
data () {
const
return {
provinces: [],
form: {
province_id: undefined
}
}
},
}
Vue.component('v-select', VueSelect.VueSelect);
new Vue({
el: '#app',
data() {
return {
provinces: [
{ name: 'province 1', province_id: 'p_1' },
{ name: 'province 2', province_id: 'p_2' },
{ name: 'province 3', province_id: 'p_3' },
],
form: {
province_id: ''
}
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!-- use the latest vue-select release -->
<script src="https://unpkg.com/vue-select#latest"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-select#latest/dist/vue-select.css">
<div id="app">
Selected {{ form.province_id }}
<v-select
v-model="form.province_id"
name="province_id"
:options="provinces"
:reduce="province => province.province_id"
label="name"
:clearable="false"
:searchable="true" />
</div>

Extract Data from JSON and display in SWAL alert

I am having problems while trying to show info from a Json to an alert, this is my code.
function check_values_chbx(){
var pre_insc = [];
}).done(function(response){
for(i=0; i<response.length; i++){
pre_insc[i] = response[0]['personas'][i]['name']+" "+response[0]['personas'][i]['ap_pat']+" "+response[0]['personas'][i]['ap_mat'];
}
alert(pre_insc[1]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n"+pre_insc.join('\n')+"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
}else {
location.reload();
}
});
});
}
And this is my JSON
[
{
"personas": [
{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [
{
"name": "Carrera larga"
}
],
"categoria": [
{
"name": "Juvenil"
}
]
}
]
I need to print each name like:
swal("name1\n"+name2\n"+etc").
Please if someone could help me it will be very helpful, have a nice day.
You can use the below script which recursively iterates a json object if it finds an array or Object until it finds the text for the given property and then print them all if the property name is name with \n separator, you can add the following inside your script file and pass it the response that you are receiving and use the returned names with your sweetAlert, just make sure you pass the response to the function like below
names = jsonParser.getNames(response[0]);
Add the below in you script
var jsonParser = {
isObject: function (property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function (property) {
return property && {}.toString.call(property) === '[object Array]';
},
getNames: function (errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.getNames(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
An example to read the names from your given response is given below.
var jsonParser = {
isObject: function(property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function(property) {
return property && {}.toString.call(property) === '[object Array]';
},
convertToString: function(errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.convertToString(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
var response = [{
"personas": [{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [{
"name": "Carrera larga"
}],
"categoria": [{
"name": "Juvenil"
}]
}];
var names = '';
names = jsonParser.convertToString(response[0]);
console.log(names);
Your final script should look like
function check_values_chbx(){
var pre_insc = [];
}).done(function (response) {
var names = jsonParser.getNames(response[0]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n" + names +
"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
} else {
location.reload();
}
});
});
Hope this helps you out

Categories