Upload File with ajax PHP Vuejs - php

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/');
?>

Related

jquery ajax FormData file Upload

Im getting a empty file response when sending the formData in ajax, It has a fileupload and some input fields. I get the response in input fields but in file upload its empty. See picture below for code.
<div class="form-group">
<label for="attachments" class="control-label col-xs-1" style="padding: 0px 0px;">Add attachments</label>
<div class="col-lg-8">
<input type="file" name="attachments[]" id="attachments" class="custom-file-input" accept="application/pdf" multiple>
</div>
<div class="col-lg-8">
<input type="text" name="name_file" id="name_file">
</div>
$("#acpl_submit").on("submit", function() {
var formData = new FormData(this);
formData.append("test", "test");
$.ajax({
type: 'POST',
// enctype: 'multipart/form-data',
url: URL,
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log(data);
},
error: function (data)
{
console.log('Error:', data);
}
});
return false;
});
PHP file, returning the POST data for checking.
public function save_accomp() {
return response()->json(request()->all());
}

Laravel 405 method not allowed in live hosting

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

Why aren't the Attachments in my Contact Form coming through? [duplicate]

This is my HTML which I'm generating dynamically using drag and drop functionality.
<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>
<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
This is my JavaScript code:
<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);
$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.

Add image to post using Ajax and Laravel 5.4

I'm trying to add an image to a post with Ajax / Laravel 5.4.
This is my HTML:
<form class="comments-form" action="/upload/comments/{{$post->id}}" method="post" data-id ="{{$post->id}}" enctype="multipart/form-data">
#csrf
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
Here is the Ajax code:
$('.add-comment').click(function(){
var comment_data = $('.comments-form').serialize();
var post_id = $('.comments-form').data('id');
var formData = new FormData('.comments-form');// i think here is problem
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,formData,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
This doesn't work – what am I doing wrong?
The FormData constructor takes a form not a string(you passes a css selector)
var formData = new FormData($('.comments-form').get(0));
If you use FormData in this way all fields in the form will be automatically added to the FormData object.
If there are items outside of the form fields that needs to be sent use the append method
formData.append('comment_data', $('.comments-form').data('id'));
When passing a FormData object to jQuery ajax you pass it alone and add processData and contentType set to false
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: formData,
contentType: false,
preocessData: false,
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
If you want to store data using ajax.. you shouldn't need to put your action in your form component
<form class="comments-form" data-id ="{{$post->id}}">
{{ csrf_field() }}
<div class="user-picture">
<img src = '/images/avatars/{!! Auth::check() ? Auth::user()->avatar : 'null' !!}'>
</div>
<div class="comment-input">
<textarea name="comment" rows="8" cols="80" placeholder="Write a Comment"></textarea>
<input type="file" name="meme" value="">
</div>
<div class="comment-button">
<button class = 'add-comment' type="button" name="add-comment">Post</button>
</div>
</form>
I think if you want to submit your form, better to use jquery submit method
$('.add-comment').submit(function(){
var post_id = $('.comments-form').data('id');
var comment_data = new FormData($(".comments-form")[0]);
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
},
method: 'POST',
url: '/upload/comments/' + post_id,
data: comment_data,
dataType: 'json'
success: function(data)
{
console.log(data);
$('.all-comments').append(data);
},
error: function(data)
{
console.log('error');
}
});
you can solve it as the following:
var formData = new FormData($("#FormId")[0]);
$.ajax({
url: '/upload/comments/' + post_id,
type: "POST",
data: formData,
processData: false,
contentType: false,
dataType: 'application/json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function (data, textStatus, jqXHR) {
console.log(data);
$('.all-comments').append(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error');
}
});
return false;
the formData variable contains all data of the form if you want to send the post id with the data sent you can put hidden field inside form called post id
like this
<input type="hidden" name="post_id" value="{{$post->id}}">
and then apply the above code

why I can't post to laravel rout using jquery?

I'm trying to submit a single value as following?
HTML:
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" name="frmanalyse" id="frmanalyse">
{{ csrf_field() }}
<label for="marginsource" style="float: left; width:150px; text-align:left;">Margin Source</label>
<input type="file" name="marginsource" id="marginsource" >
<br />
</form>
script:
<script type="text/javascript">
$( "#frmanalyse" ).submit(function(event) {
$.post( "marginanalyser", {username: "medo ampir"}, function( data ) {
alert(data);
});
event.preventDefault();
});
in laravel routes:
Route::post('marginanalyser',function(Request $request){
echo $request->input('username');
$file = $request->file('marginsource');
echo 'File Name: '.$file->getClientOriginalName();
});
nothing shows in the message at all.
Change your JavaScript to use FormData as you aren't submitting the file
$( "#frmanalyse" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('marginsource', $('#marginsource')[0].files[0]);
formData.append('username', "medo ampir");
$.ajax({
url : window.location.origin + "/marginanalyser",
type: "POST",
data : formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
});

Categories