Since a lot of days I am trying to upload file in the server I got 405 methods not allowed error in live server:
This is my view:
HTML & javascript
#extends('layouts.app')
#section('content')
form id="uploaddiamond" class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
#csrf
<div class="col-md-6">
<div class="block">
<div class="panel-body">
<div class="form-group">
<label class="col-md-3 control-label">Upload Diamond <span class="required">*</span></label>
<div class="col-md-9">
<input required="" type="file" name="result_file" id="result_file" />
</div>
</div>
<div class="btn-group pull-right">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
#endsection()
#section('javascript')
<script>
$("#uploaddiamond").on("submit",function(e) {
e.preventDefault();
console.log('tst');
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
});
var file_data = $('#result_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "{{ route('diamond') }}", // point to server-side PHP script
data: form_data,
type: 'POST',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false,
success: function(data) {
console.log(data);
}
});
});
</script>
#endsection()
This is my web route:
Route::get('/imageview','ImageController#index')->name('getimage');
Route::post('/postDiamond','ImageController#postDiamond')->name('diamond');
This is my controller:
public function index(){
return view('Image/imgupload');
}
public function postDiamond(Request $request){
dd($request->file('file'));
$supplier_name = $request->supplier_name;
$extension = $request->file('file');
$extension = $request->file('file')->getClientOriginalExtension(); // getting excel extension
$dir = 'assets/files/';
$filename = uniqid().'_'.time().'_'.date('Ymd').'.'.$extension;
$request->file('file')->move($dir, $filename);
}
I don't why this code is not working cause this code works in localhost but, not working in Linux hosting:
Can someone help do I have did a mistake on version something
server current PHP version:7.3.17
laravel PHP version:7.1.10
This is my server error image please check:
enter image description here
enter image description here
Well I have just tested this code on live server and it's working fine. If this code still doesn't work for you then you need to check permissions on server side for some files like web.php etc...
$(document).on('click','#submit_button', function(e){ //#submit_button id on submit button
e.preventDefault();
var formData = new FormData(this.form);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
method: 'POST',
url: '{{ route("diamond") }}',
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
});
Be sure to remove #csrf from your <form> tag.
In controller just dd(request()->all()); and see what you get
Related
So im building my own website and i have this feature wherein a logged-in user can upload and change his avatar. it is my first time doing this so i am having a hard time making this work. i'll provide the codes below, you guys might see the faults that i dont know. it will be greatly appreciated if you can provide links that will help me improve. thanks in advance!
Blade.php file
<form method='POST' action="{{ route('image-upload') }}" enctype="multipart/form-data">
#csrf
<div class=" overflow-auto" style="padding-top:5%">>
<div class="p-3">
<div class="card">
<div class="card-body" >
<h4 class="card-title text-info"><strong> Attach your picture </strong></h4>
<div class="row justify-content-center">
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="step5_picture" class="col-sm-3 text-right control-label col-form-label">Please upload your photo here:</label>
<div class="col-sm-9">
<input class="form-control" type="file" value="" id='upload_picture' >
</div>
</div>
</div>
</div>
Next
<button class="btn btn-lg waves-effect waves-light btn-info" id="btn-upload" style="float:right; margin-right:10px;">Upload</button>
</div>
</div>
</div>
</div>
</form>
Ajax code
$("#btn-upload").click(function(e){
e.preventDefault();
var data = {
'photo_filename': $('#upload_picture').val(),
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/image-upload",
data: data,
dataType: "json",
success: function (response) {
}
});
});
});
Controller.php file The name of the column in my database is also photo_filename
public function image-upload(Request $request,){
$data = UserInfoModel::where('app_id', '=' ,Session::get('loginId'))->first();
$validator=Validator::make($request->all(), [
'photo_filename' => 'required',
'photo_filename.*' => 'image|mimes:jpeg,png,jpg,svg|max:5000'
]);
if($request->hasfile('photo_filename')){
$data->update([
'photo_filename' => $request->input('photo_filename')
]);
$photo = $request->file('photo_filename')->getClientOrginalName();
$destination = public_path() . '/public/image';
$request->file('photo_filename')->move($destination, $photo);
return back()->with('success', 'Your image has been successfully uploaded!');
}
}
Web.php file
Route::post('/image-upload',[CustomAuthController::class, 'image-upload'])->name('image-upload');
I am getting a payload and here it is
No error but still not uploading
Here's a minimal working example to create file upload in Laravel:
blade file:
<form method="POST" enctype="multipart/form-data" action="{{ route('save') }}">
#csrf
<input type="file" name="image" placeholder="Choose image" id="image">
<button>Send</button>
</form>
Controller:
public function save(Request $request) {
$path = $request->file('image')->store('public/images');
return $path;
}
web.php:
Route::post('/foobar', [\App\Http\Controllers\FoobarController::class, 'save'])->name('save');
Please note Ajax call is not necessary here, since html form will do the POST call with the CSRF token.
Also please note that using hyphens in function names won't work in php.
use FormData to send file in form, and add contentType: false and processData: false, you can read function setting contentType and processData in here https://api.jquery.com/jquery.ajax/
var formData = new FormData();
formData.append('photo_filename', $('#upload_picture')[0].files[0])
$.ajax({
url: "/image-upload",
type: "post",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response) {
}
});
I want to POST and upload image via AJAX with Google reCaptcha v2 validation. but I am facing an issue that I am not not able to send image with caption text with google recaptcha token in Ajax. I coded two function as I know but both was not working. The function I made is the code snippet.
Please help me how I send Image with text in Ajax with reCaptcha token in PHP / jQuery/ AJAX.
$(document).ready(function() {
$("form#addbanner").unbind("submit").bind("submit", function(e) {
//debugger;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('MY_RECAPTCHA_CODE', {
action: 'add_web_banner'
}).then(function(token) {
/*let formData = {
imagehere : $('input[name="imagehere"]').val(),
bannertitle : $('input[name="bannertitle"]').val(),
action : 'add_web_banner',
type: 'add_web_banner'
};*/ //not working
/*let formData = {
var formData = new FormData($("form#addWeb-Banner")[0]);
formData.append('token': token);
};*/ //not working
//*POST Image sent in (binary way), I dont want to use JSON in types*//
$.ajax({
type: 'POST',
data: formData,
cache: false,
success: function(response) {
hide_loader();
if (response.status == "success") {
$("form#addWeb-Banner")[0].reset();
alert("Great");
} else {
alert("Ops!");
}
},
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="bs-example form-horizontal AddWebBanner" id="addbanner" enctype="multipart/form-data" method="POST">
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Upload Image</label>
<div class="col-lg-8">
<input type="file" class="form-control" title="Upload Photo" id="BannerImage" name="imagehere" accept="image/png,image/jpg,image/jpeg" />
</div>
</div>
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Caption of Banner</label>
<div class="col-lg-8">
<input type="text" class="form-control" title="Caption of Banner" name="bannertitle" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-lg-12">
<button type="submit" name="submit" class="btn btn-sm btn-default pull-right" id="addBannerBtn">POST</button>
</div>
</div>
</form>
Change your HTML and formData to the following
Give an id selector your caption banner.
<input type="text" class="form-control" id="caption_banner" title="Caption of Banner" name="bannertitle" />
Store using the formData like this and then sent formData via ajax
var formData = new FormData();
//Append Image
formData.append('file', $('#BannerImage')[0].files[0]);
//Append banner caption
formData.append('caption', $('#caption_banner').val());
You can also use jQuery .serialize method to send data to your backend via ajax
var formData = $('form#addbanner').serialize()
thank for #AlwaysHelping but there was one mistake but I has been fix that..below are the correct answer for future user troubles..
I not mentioned processData: false, contentType: false, in ajax.. so the final code will be..
var formData = new FormData();
formData.append('file', $('#BannerImage')[0].files[0]);
formData.append('caption', $('#caption_banner').val());
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (response) { ... }
peace :)
i just wanted to upload an image using ajax and codeigniter. Getting error which is saying "You did not select a file to upload." even i did select that image.
I recently tried many examples from many sources but did not get my answer. following i show you my code this is giving me the result as "You did not select a file to upload." when i already selected the file.
This is my view:
<div class="col-lg-6">
<div class="dropify-wrapper mb-4 form-group col-lg-6">
<div class="dropify-loader"></div>
<div class="dropify-errors-container">
<ul></ul>
</div>
<input class="dropify" name="userfile" id="input-file-now" type="file">
<button class="dropify-clear" type="button">Remove</button>
<div class="dropify-preview">
<span class="dropify-render"></span>
<div class="dropify-infos">
<div class="dropify-infos-inner">
<p class="dropify-filename"><span class="file-icon"></span>
<span class="dropify-filename-inner"></span></p>
<p class="dropify-infos-message">Drag and drop or click to replace</p>
</div>
</div>
</div>
</div>
</div>
This is ajax code:
$('#submit_btn').click(function (e) {
e.preventDefault();
var data = $('#formname').serialize();
$.ajax({
type: 'ajax',
method: 'post',
url: '<?php echo base_url() ?>ControllerName/functionName',
data: data,
enctype: 'multipart/form-data',
async: false,
dataType: 'json',
success: function (response) {
alert(response);
},
error: function () {
}
});
});
This is controller code:
public function functionName()
{
$config=[
'upload_path'=>'./Assets/imgs/users/',
'allowed_types'=>'jpg|png|gif'
];
$this->load->library('upload',$config);
if($this->upload->do_upload(')){
$data=$this->upload->data();
$image_path= base_url("Assets/imgs/users/".$data['raw_name'].$data['file_ext']);
$result= $image_path;
}else{
$result=$this->upload->display_errors('','');
}
}
Please add tag in your html and also use formdata in jquery code like below.
HTML Code:
<form id="form" method="post" enctype="multipart/form-data">
</form>
Jquery Code:
data: new FormData(formid),
Hey everyone Im trying to upload a file with ajax. I am also passing an username to get inserted into a database. In previous forms I've been using vuejs to run a fiction on submit rather than actually submitting the form with php. As I json encode everything and it requires no refresh.
heres my form the problem is I cant get the file upload to work.
<div id="app">
<form role="form" onsubmit="return false">
<div class="form-group">
<label>Username</label>
<input type="text" placeholder="Username" v-model="userName" name="userName" class="form-control>
</div>
<div class="form-group">
<label>File</label>
<input type="file" #change="processVideoFile($event)" id="uploadVideoFile">
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
userName: '',
uploadVideoFile:''
methods: {
processVideoFile: function() {
this.uploadVideoFile=$('#uploadVideoFile').val();
},
addTemplate: function(){
this.sub=true;
var jsonString = JSON.stringify({
uploadVideoFile: this.uploadVideoFile,
userName: this.userName
});
if(this.userName!=''){
$.ajax({
url: 'addTemplateBackend.php',
dataType: 'json',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: jsonString,
error: function(data){
alert('error');
},
success: function(data){
console.log(data);
alert('success');
}.bind(this)
});
}
},
}
});
</script>
add templates backend
<?php session_start(); ob_start();
require_once('database.php');
$requestBody = file_get_contents('php://input');
$requestJSON = json_decode($requestBody);
$data=json_encode($requestJSON);
echo $data;
move_uploaded_file($requestJSON->uploadVideoFile, 'www.somesite.com/braiden/braintree/');
?>
I have a form in which I am taking file input that is image, then I send data to my controller with a ajax call but my controller is not getting any file. It is showing me the error {"error":"You did not select a file to upload.</p>"}
My Form
<form action="#" id="formParking" enctype="multipart-form-data">
<div class="input-group">
<div class="col-xs-12 col-sm-4 no_padding">
<label class="">Attachment</label>
</div>
<div class="col-xs-12 col-sm-8">
<div class="col-xs-12 no_space"><input type="file" id="images" name="images" multiple="multiple" /></div>
</div>
</div>
<div class="input-group">
<div class="col-xs-12 col-sm-4 no_padding"> </div>
<div class="col-xs-12 col-sm-8"> <a class="btn blue green text-center" id="btnSave" onclick="saveParking()" >Add</a> </div>
</div>
</form>
Ajax Call
function saveParking()
{
var url;
url = "link_to_controller_function";
$.ajax({
url : url,
type: "POST",
data: $('#formParking').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
My Controller
$config['upload_path'] = base_url().'uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 11111;
$config['max_height'] = 76118;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('images'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
echo json_encode($data);
}
Addd processData and contentType in your ajax to deal with form when you are posting it using ajax
$.ajax({
url : url,
type: "POST",
data: $('#formParking').serialize(),
dataType: "JSON",
processData: false,
contentType: false,
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
also add this attribute enctype="multipart/form-data" to your form tag as
<form action="#" id="formParking" enctype="multipart/form-data">
correct this
enctype="multipart/form-data"
it seems there is the problem with your ajax code, please use FormData instead of serialize for file upload.
Example:
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#gallery").html(data);
},
error: function(){}
});
}));
For more info See: http://phppot.com/jquery/php-ajax-multiple-image-upload-using-jquery/
the ajax submission
$("#ID").submit(function(e){
e.preventDefault();
var formData = new FormData(this);
jQuery.ajax({
url : $(this).attr('action') or url,
type : $(this).attr('method') or method,
data : formData,
success:function(response){
//do whatever you want
},
cache: false,
contentType: false,
processData: false
});
});
Your Have to change
$config['upload_path'] = base_url().'uploads';
to
$config['upload_path'] = './uploads/';
on base_url().'uploads' you are pointing the path to a website.
and of course you have to create uploads directory In root.