I try to change value of my column in users table with x-editable and I get 419 error on network.
codes
here is my CONTROLLER
public function changeprimaryaddress(Request $request){
try {
$id = $request->input('pk');
$field = $request->input('name');
$value = $request->input('value');
$user = User::findOrFail($id);
$user->{$field} = $value;
$user->save();
} catch (Exception $e) {
return response($e->getMessage(), 400);
}
my ROUTE
Route::post('/changeprimaryaddress','UserController#changeprimaryaddress')->name('changeprimaryaddress');
my HTML code
<a href="#"
class="change"
data-type="select"
data-name="address_id"
data-pk="{{ $user->id }}"
data-value="{{ $user->address_id }}"
data-title="Select New Primary Address"
data-url="{{ route('changeprimaryaddress') }}">Change</a>
my JAVASCRIPT
<script type="text/javascript">
$(function() {
$('.change').editable({
source: [
#foreach($addresses as $address)
{ value: '{{ $address->id }}', text: '{{ $address->address }} - {{$address->city->name}}, {{$address->state->name}}, {{$address->country->name}}, {{$address->postalcode}}' }
#unless ($loop->last)
,
#endunless
#endforeach
]
});
});
</script>
screenvideo
If you like to see the process and errors i provided small video you can see.
result
any idea why is that?
thanks to #SagarGautam. I added
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
its working now.
It is because you are not sending csrf token to the controller. either send the token, or do the following to exclude it.
open your app/Http/Middleware/VerifyCsrfToken.php file, and put the below code:
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'changeprimaryaddress',
];
}
Related
I want to upload multiple image files and send it via email to customers. But the ajax request get this error call to a member function getclientoriginalname() on array when uploadMultiple: true, added to dropzone. Multiple images uploaded without that option. Anyway i want to email that multiple files, how can i do this?
dropzone js code:
Dropzone.options.uploadimg = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, //MB
acceptedFiles: ".jpeg,.jpg,.png",
uploadMultiple: true,
addRemoveLinks: true,
success: function(file, response)
{
$.notify({
message: 'Image uploaded Successfully!'
},
{
type: 'success'
});
},
error: function(file, response)
{
return false;
console.log('fail to upload');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
}
SendMailController to send uploaded images.
public function sendNotifications(Request $request)
{
$id_int = Cookie::get('jobid');
$img_name = Cookie::get('imgName');
$data = DB::table('customers')
->join('jobs', 'jobs.id', '=', 'customers.id')
->select('firstname','email')
->where('jobs.id', '=', $id_int)
->get()->toArray();
foreach ($data as $value) {
$customer_firstname = $value->firstname;
$customer_email = $value->email;
}
$pathToFile = public_path() . "\\uploads\\" . $img_name;
//send the email to the relevant customer email
Mail::to($customer_email)->send(new SendMail($customer_firstname, $pathToFile), function($message){
$message->attach($pathToFile);
});
}
Image upload controller:
class ImageUploadController extends Controller
{
public function uploadImage(Request $request){
$img_file = $request->file('file');
$imgName = $img_file->getClientOriginalName();
Cookie::queue(cookie('imgName', $imgName, $minute = 5));
$img_file->move(public_path('uploads'), $imgName);
}
}
When i uploaded multiple images and sendinding via email, it only send the last uploaded file in dropzone. How can i send all uploaded files?
since its multiple files you need to loop through the file variable to get the files
class ImageUploadController extends Controller
{
public function uploadImage(Request $request){
$img_files = $request->file('file');
foreach($img_files as $img_file){
$imgName = $img_file->getClientOriginalName();
Cookie::queue(cookie('imgName', $imgName, $minute = 5));
$img_file->move(public_path('uploads'), $imgName);
}
}
}
I'm trying to build a simple website builder that allow users to save their generated html created with Vue component and see it at a certain URL.
Because of it I have to store and retrieve the html generated but I have some problems with retrieving of the code. Here is my step:
When user click "save" this function is fired, that select the portion of HTML that include the "website" built by the user:
saveBuilders: function () {
let pages = [];
let builders = $('[id*="builder-container-"]');
$.each(builders, function (key, builder) {
let singleElem = $(builder).attr('id');
pages.push(clearElement.html());
});
this.storeInDb(pages);
},
storeInDb: function (pagesList) {
axios.post("/landing-page/store", {
name: this.name,
description: this.description,
html: pagesList
})
.then(function (response) {
console.log('Cool');
})
.catch(function (error) {
console.log('ERROR', error.response);
});
},
The Axios request is handled by this function that store the html portion in DB
public function store(Request $request)
{
$data = $request->all();
$html = $data['html'];
$landingPage = new LandingPage();
$landingPage->name = $data['name'];
$landingPage->description = $data['description'];
$landingPage->user_id = Auth::user()->id;
$landingPage->html = json_encode($html);
try {
$landingPage->save();
return 'true';
} catch (exception $e) {
return $e;
}
}
Now when the user visit a certain URL, for keep thing simple suppose is example.it/website/0, this function is fired:
public function show($landing_id)
{
try {
$landingPage = LandingPage::where([
'id' => $landing_id,
'user_id' => Auth::user()->id
])->first();
} catch (\Exception $e) {
$landingPage = null;
}
if ($landingPage != null) {
//GET THE HTML
$page = json_decode($landingPage->html);
return view('landing_page.show')->with('page', $page)
} else {
abort(404, 'Error');
}
}
And this the blade where I'm trying to re-create the Vue.js environment
<body>
<span id="countdown"></span>
<div id="builder-pagina">
<builder>
{!! $page !!}}
</builder>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="{{asset('js/landing_page/app.js')}}"></script>
</body>
</html>
I thought that having the html generated by vue similar to something like that into the DB...
<div data-v-29b64d26="" >
<h1>This piece of code was stored into my DB</h1>
<div data-v-56f62f0a="">
</div>
</div>
...you could create everything working simply by pasting the code and by using the same js file used for compiling vue.js.
I've tried pass the entire code by props but is not working. Also tried with slot. Any suggestions?
I'm usin react.js(ver 15) and i want to upload the files with yii2 api.
My code is as follows:
My component(in react):
import React, { Component } from 'react';
import Header from './Heaader';
/* global $ */
class New extends Component {
constructor(props){
super(props);
this.state = {
cates: [],
subcats: [],
radioSelected: "f"
};
}
submitted = (e) => {
e.preventDefault();
var file_data = $('#filee')[0].files;
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "http://blog.dev/ads",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
},
error: function(){}
});
};
render(){
return (
<div>
<Header isNew="true" />
<div style={{marginTop: 2 + 'em'}}>
<form onSubmit={this.submitted}>
<input type="file" id="filee" />
<button type="submit">Sub</button>
</form>
</div>
</div>
);
}
Server Side:
In my controller:
<?php
namespace frontend\controllers;
use Yii;
use yii\rest\ActiveController;
class AdsController extends ActiveController
{
public $modelClass = 'frontend\models\Ads';
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
public function actions()
{
$actions = parent::actions();
unset($actions['create']);
return $actions;
}
public function actionCreate()
{
print_r($_FILES);
}
}
My problem is that $_FILES array is empty!
When I send data other than the file, $_POST works without problems(While this is the case in ajax request: processData:true and contentType:true ).
but $_FILES is empty.
Please guide me and tell me where the problem is?
Make sure your form has the correct encoding i.e <form enctype=multipart/form-data> for file uploads. this is most likely the reason why your $_FILES is empty
Yii 2 specifies a uniform API for fetching/saving uploads by using UploadedFile::getInstance($model, 'imageFile'); from the yii\web\UploadedFile; You should use it to access the uploads.
All the Best
Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this
var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js
example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK
Controller
class SearchCompanyName extends Controller
{
public function getcompanyname($name)
{
return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
}
public function index()
{
$url = $this->getcompanyname(Input::get("company_name_by_user"));
return view('searchcompany', ['url' => $url]);
}
}
vue app.js
Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
el: '#search',
data: {
},
method: {
getMessages: function(){
console.log('I am here')
}()
}
});
blade template
#section('content')
<div class="container">
{!! $url !!}
<search></search>
</div>
#endsection
If you want to declare your javascript variable in a script tag within a blade file, you need to put the variable in quotes like so
<script>
var url = '{{ $url }}';
</script>
You can use this package : https://github.com/laracasts/PHP-Vars-To-Js-Transformer
public function index()
{
JavaScript::put([
'foo' => 'bar',
'user' => User::first(),
'age' => 29
]);
return View::make('hello');
}
I can save all data varchar/text element from my form, but I can't save my path image.
Whats is wrong with my code?
Lets see my create.blade.php I can save value of var deadline but I can't save value of var path:
Form::open(array('url' => 'imagesLoker', 'files' => true))
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
{!!Form::label('Deadline Lowongan : ')!!}
{!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
</div>
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('path') !!}
</div>
</div><!-- /.box-body -->
</form>
{!!Form::close()!!}
This is my Controller:
public function store(Request $request)
{
Lowongan::create($request->all());
return "data all";
}
This is my Ajax to create the data:
$("#createLoker").click(function(){
var datas = $('form').serializeArray();
var route = "http://localhost:8000/lowongan";
var token = $("#token").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post(route,{
deadline: $("#deadline").val(),
path: $("#path").val()
}).done(function(result){
console.log(result);
});
});
I don't know this is important or no to setting parse data in my Modal, but I just put this code in my Modal:
class Lowongan extends Model
{
protected $table = 'Lowongan';
protected $fillable = ['path','deadline'];
public function setPathAttribute($path){
$this->attributes['path'] = Carbon::now()->second.$path->getClientOriginalName();
$name = Carbon::now()->second.$path->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($path));
}
}
And the last I set the directory to save the image. This is setting in the config/filesystem:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imagesLoker'),
],
I can save the data deadline but no for image :( .. If there is any idea for how to save the image path, I will be pleased to know it.
In your form you have to allow file upload option in laravel like.
Form::open(array('url' => 'foo/bar', 'files' => true))
check the file upload section of laravel doc
Hope it helps..
please follow these steps
in view
change {!!Form::file('path') !!} to {!!Form::file('file') !!}
In controller
please note i have set the upload path to root/public/uploads/ folder
public function store(Request $request)
{
$file = Input::file('file');
$path = '/uploads/';
$newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
// Move the uploaded file
$upSuccess = $file->move(public_path() . $path, $newFileName);
$result = file_exists(public_path() . $path . $newFileName);
$fileData =[
'fileType' => $file->getClientOriginalExtension(),
'filePath' => substr($path, 1) . $newFileName
];
Input::merge(array('path' => $fileData["filePath"]));
Lowongan::create($request->all());
return "data all";
}