Save path image with Ajax in Laravel - javascript

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";
}

Related

Create post and upload image with Ajax (axios) in Wordpress

So I want my users to be able to create a post in the frontend and upload an image with a form I've created.
When the image is uploaded I want to update an ACF-field with the uploaded image.
I've seen some posts on this but none of them are explained any good.
I want to use Ajax and I want to use axios, so please no jQuery. I also use Qs.
The image itself is never uploaded but the file name is inserted in the media library.
Thank you!
HTML
<form enctype="multipart/form-data" method="post" id="register-store-form">
<fieldset class="store-images mb-3">
<label for="store-images">Add images</label>
<input type="file" id="store_images" name="store_images" accept="image/png, image/jpeg">
</fieldset>
<button class="btn btn-primary" id="update-store">Save store</button>
</form>
JS
const Qs = require('qs');
const axios = require('axios');
const saveStoreBtn = document.querySelector('#update-store');
const addStore = document.querySelector('#add-one-more-store');
function saveStore(e) {
const storeName = document.querySelector('#store-name');
const storeImages = document.querySelector('#store_images');
const storeImageFile = storeImages.files[0];
const ajaxData = {
action : 'create_store',
security : shkGlobal.addStore,
name : storeName.value,
image_name : storeImageFile.name,
image_type : storeImageFile.type,
description : storeDescription.value
};
axios.post(shkGlobal.adminUrl, Qs.stringify(ajaxData))
.then(function(response) {
saveStoreBtn.innerHTML = "Thank you";
})
.catch(err => console.log('Not working', err));
};
updateStoreBtn.addEventListener('click', saveStore);
PHP
function create_store() {
check_ajax_referer('add_store', 'security');
$name_value = $_POST['name'];
$image_name = $_POST['image_name'];
$image_type = $_POST['image_type'];
$post_data = array(
'post_type' => 'store',
'post_title' => htmlentities($name_value),
'post_content' => $_POST['description'],
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_data );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES[$image_name];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'].'/'.$image_name,
'post_mime_type' => $image_type,
'post_title' => $image_name,
'post_content' => 'File '.$image_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('field_602019eba7767', $attach_id, $post_id);
}
echo json_decode($response);
exit;
}
add_action('wp_ajax_create_store', 'create_store');
add_action('wp_ajax_nopriv_create_store', 'create_store');
There are two problems in your case, first one that you are uploading multiple files, so structure of $_FILES will be different. Second one is that you specified store_images instead store_images[] for multiple file upload.
So in html change <input type="file" name="store_images" multiple> to <input type="file" name="store_images[]" multiple>
And in php, change your code accordingly to example below.
$files = $_FILES['store_images];
foreach ($files as $key => $value) {
if ($files['name']) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
wp_handle_upload($file);
}
}
}

Can't upload image only on mobile device Laravel + Vue

I read about this on some posts on the stack, but I still do not see the same case as mine. I can not upload the image on phone device. I do not see why I do not have a console to see error. I'll show you the code, so someone who is experienced can see the error.
Laravel code to upload image:
public function uploadImage($car, $images)
{
$fileName = Carbon::now()->timestamp . $images->getClientOriginalName();
$path = $images->move(public_path('public/images'), $fileName);
if (!$path) {
return response()->json(['message' => 'An error has accured'], 500);
}
$carImage = new CarImages ([
'path' => 'public/images/' . $fileName
]);
$car->images()->save($carImage);
return $carImage;
}
Laravel code for store form with image:
public function store(CarRequest $request)
{
$file = null;
if ($request->has('picture')) {
$file = $request->file('picture');
}
$user = auth()->user();
if ($user) {
$car = Car::create([
'car_type' => $request->input('car_type'),
'mark' => $request->input('mark'),
'model' => $request->input('model'),
'user_id' => $user->id
]);
}
if (!$car) {
return response()->json(['message' => 'Oooops, something went wrong'], 500);
}
if ($file) {
$carImage = $this->uploadImage($car, $file);
}
Mail::to($user->email)->send(new NotifyNewCarUpload($user, $car));
return response()->json([
'message' => 'Your car has been successfully added',
'car' => $car,
'user' => $user
], 201);
}
In CarRequest for upload for car i have:
'car_type' => 'required',
'mark' => 'required',
'model' => 'required',
'picture' => 'required|image'
In Vue.js insert car I have:
<form enctype="multipart/form-data" accept-charset="utf-8"
#submit.prevent="submit">
...
...
<div class="col-3 insert-vehicle-right">
<div :class="{ 'error': errors.has('file') }" v-if="!imgSrc" class="image-upload-holder"></div>
<img :class="{ 'error': errors.has('file') }" v-if="imgSrc" class="uploaded-image" :src="imgSrc" alt="uploaded image"/>
<div class="upload-btn-wrapper">
<button class="btn action-btn">Upload Photo</button>
<input name="file"
v-validate="'required'"
type="file"
#change="onFileChange"/>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" class="btn action-btn save-btn">Save</button>
</div>
</form>
Vue.js javascript code for upload and preview image code:
onFileChange(event) {
this.picture = event.target.files[0];
const file = event.target.files[0];
this.imgSrc = URL.createObjectURL(this.picture);
},
And i have formData code for post that code:
...
...
formdata.append('picture', this.picture);
It's not working on mobile phones. Does anyone recognize the reason?
All my pictures are stored in the laravela folder public/public/images and work good on web browser (destop and laptop device). Also i have table for storing path images.. Only for phone device not work. Help?
Okey problem was be in php.ini configuraction and max_size_upload file. I only set more than 2mb images file and work perfecty.
#thanks Rasa

How to pass a variable from laravel 5.4 to vuejs

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');
}

How to retrieve data using ajax and without going to post page? Laravel 5

I'm new to using ajax. For example after field title is filled, I want to search in database for specific data and return more fields based on that input. So far I can only receive my title data in /ajax/post page by pressing get data/post data or submit button. How do I receive my title input and data from Route::post while/after filling title? If I remove Form::model and Form::close() I do get my dummy data from Route::post without page refresh by clicking Post data button, but without title value.
I'm aware that checking title field involves some jQuery/js, but I have no idea how to actually bring that title field into my route to do some database searching and return some data with it.
View:
{!! Form::model($project = new \App\Project, ['url' => 'ajax/post', 'method' => 'post']) !!}
<!-- pass through the CSRF (cross-site request forgery) token -->
<meta name="csrf-token" content="<?php echo csrf_token() ?>" />
<!-- some test buttons -->
<button id="get">Get data</button>
<button id="post">Post data</button>
<div class="form-group padding-top-10">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title']) !!}
</div>
{!! Form::submit('Submit Button', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
Ajax script:
<script>
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
function onGetClick(event)
{
// we're not passing any data with the get route, though you can if you want
$.get('/ajax/get', onSuccess);
}
function onPostClick(event)
{
// we're passing data with the post route, as this is more normal
$.post('/ajax/post', {payload:'hello'}, onSuccess);
}
function onSuccess(data, status, xhr)
{
console.log(data, status, xhr);
// JSON is deserialised into an object
console.log(String(data.value).toUpperCase())
}
$('button#get').on('click', onGetClick);
$('button#post').on('click', onPostClick);
</script>
And in route:
Route::get('/ajax/view', ['as' => 'home', 'uses' => 'AjaxController#view']);
Route::get('/ajax/get', function () {
$data = array('value' => 'some get');
return Response::json($data);
});
Route::post('/ajax/post', function () {
$data = array('value' => 'some data', 'input' => Request::input());
return Response::json($data);
});
What you need is to implement the jquery keypress function.
so here is you js:
$("input.title").keypress(function(){
var title = $(this).val();
// now do the ajax request and send in the title value
$.get({
url: 'url you want to send the request to',
data: {"title": title},
success: function(response){
// here you can grab the response which would probably be
// the extra fields you want to generate and display it
}
});
});
as far as in Laravel you can pretty much treat it the same as a typical request except you will return json:
Route::get('/url-to-handle-request', function({
// lets say what you need to populate is
//authors from the title and return them
$title = Route::get('title'); // we are getting the value we passed in the ajax request
$authors = Author::where('title' ,'=', $title)->get();
return response()->json([
'authors' => $authors->toArray();
]);
}));
Now I would probably use a controller and not just do everything within the route but I think you'll get the basic idea.

Download a file on page load in Jquery

I have a file in my server folder and now I want to download that file on page load.
Example :
If I click on Our products than a file has been downloaded automatically in users system from my server.
// in controller
public function download() {
$this->viewClass = 'Media';
// Render app/webroot/files/example.docx
$params = array(
'id' => 'example.docx', // file name
'name' => 'example',
'extension' => 'docx', // its file extension name
'mimeType' => array(
'docx' => 'application/vnd.openxmlformats-officedocument' .
'.wordprocessingml.document'
),
'path' => 'files' . DS
);
$this->set($params);
}
//In view file
echo $this->Html->url(array(
"controller" => "controller_name",
"action" => "action_name",
"ext" => "file_extension_name"
));
Also read Cakephp Media View
This is my ans :
$(document).ready(function(){
if('<?php echo $filename ?>' !=''){
window.location.href ='/files/<?php echo $filename ?>.xls';
}
});
</script>

Categories