Uploading file using link instead of button but receiving $_FILES array empty - ajax

In my upload file I keep receiving the rest of the form data
but $_FILES array comes up empty. Can you guys help me with why
i'm on sending the hidden input data but no the files data ?
I have this for the link
<li><a href='#' id='upload_linko' onClick='imgUpload(1)'><i class='icon-image2'></i> Update cover photo</a></li>
And this for the form
<form id='upform' method='post' enctype='multipart/form-data'>
<input type='file' id='upload1' name='upload1' style='visiblity: hidden ; width: 1px; height: 1px' />
<input type='hidden' id='profid' name='profid' value='xyz'>
<input type='hidden' id='query_type' name='query_type' value='cover'>
</form>
and my script is like this
$(document).on('change','#upload1' , function(){
var fd = new FormData($("#upform"));
var file_data = $('input[type="file"]')[0].files;
$.each(file_data, function(key, value)
{
fd.append('file', value);
});
var other_data = $('#upform').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'xxxxxxxx.php',
type: 'POST',
data: fd,
success:function(data){
// $('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
function imgUpload(optype)
{
document.getElementById('upload1').click();
}

Related

How to display image on successful image POST?

I am currently using Ajax to POST formdata (images) to my PHP application, where I then simply save the image.
My form:
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<label>
Open file dialog
<input type="file" style="position: fixed; top: -100em" name="file">
</label>
</form>
My script:
$( document ).ready(function() {
$("#upload-pictures").click(function(){
var form = $('#fileUploadForm')[0];
var formData = new FormData(form);
$.ajax({
method: "POST",
type: "POST",
url: "http://localhost:8080/index/index.php",
enctype: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
$('body').html('<img src="' + data + '" />'); //doesn't work
}
});
});
});
What's the best way for me to display this image (after it has been successfully uploaded) on my webpage? I tried using $('body').html('<img src="' + data + '" />');
but it didn't seem to work.
Any help would be truly appreciated.
Thanks
Thanks to #RatajS for the help. I finally got it working:
In my PHP:
$contents = base64_encode(file_get_contents($_FILES['file']['tmp_name']));
In my HTML/Javascript:
$("<img>").attr({src: "data:image/jpeg;base64," +data}).appendTo("body");

AJAX - upload image with ajax without form on laravel

i try to make upload image with ajax without form, when i am sent data without the image, data successfully submitted to the database, but when i am adding an image, when i try to submit, no response at all,
this is my template code :
<input type="hidden" name="lesson_id" value="{{-- $lessons->id --}}">
<input type="hidden" name="parent_id" value="0"> -->
<div class="form-group">
<label>Komentar</label>
<textarea rows="8" cols="80" class="form-control" name="body" id="textbody0"></textarea>
</div>
<ul class="right">
<input type="file" name="image" id="image" />
<img id="myImg" src="#" />
<button type="button" class="btn btn-primary" onClick="doComment({{ $lessons->id }},0)" >Kirim</button>
and this is my script for submit data :
function doComment(lesson_id, parent_id) {
var body = $('#textbody'+parent_id).val();
var image = $('#image').prop('files')[0];
if (body == '') {
alert('Harap Isi Komentar !')
}else {
var postData =
{
"_token":"{{ csrf_token() }}",
"lesson_id": lesson_id,
"parent_id": parent_id,
"image": image,
"body": body
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
type :'POST',
url :'{{ url("lessons/coments/doComment") }}',
dataType: 'json',
data : postData,
beforeSend: function(){
// Show image container
swal({
title: "Sedang mengirim Komentar",
text: "Mohon Tunggu sebentar",
imageUrl: "{{ asset('template/web/img/loading.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
{{-- $("#loader").show(); --}}
},
success:function(data){
if (data.success == false) {
window.location.href = '{{ url("member/signin") }}';
}else if (data.success == true) {
$('#textbody'+parent_id).val('');
swal({
title: "Komentar anda sudah terkirim!",
showConfirmButton: true,
timer: 3000
});
getComments();
}
}
});
}
}
Can any one help me?
postData = new FormData();
if(!!file.type.match(/image.*/)){
postData.append("image", file);
$.ajax({
type : 'POST',
url : '{{ url("lessons/coments/doComment") }}',
data : postData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}

Joomla sending Data (special Image) with Ajax (Formdata)

Using Joomla:
My problem is when I submit the button, ajax send an empty data array back to my client. Debbuging in the console shows me that datas in the header but the preview and response values are empty.
Here is my code (I am using a modal form from bootstrap).
HTML in my default script:
<form action="<?php echo JRoute::_('index.php?option=com_addproduct&view=addproducts'); ?>" method="post" name="modalMessageForm" id="modalMessageForm" enctype="multipart/form-data">
<input type="file" id="message-image-upload" accept="image/*" style="display:none;" name="message-image-upload">
<textarea class="form-control message-textarea" id="message-textarea" placeholder="Nachricht..." name="new-message" rows="4"></textarea>
<button type="button" id="button-close-message" class="btn btn-default btn-block btn-message-close" style="display:none; margin-top:5px;"><?=JText::_( 'COM_ADDPRODUCT_MODAL_MESSAGES_CLOSE')?></button>
</form>
JQuery / Ajax:
$(document).on("submit", "#modalMessageForm", function(e)
{
var form = $('#modalMessageForm').get(0);
e.preventDefault();
var formData = new FormData(form);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
crossDomain: true,
type: "POST",
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
data: formData,
dataType: "json",
processData: false
})
.done(function(data, textStatus, jqXHR){
console.log('Message: '+data.new-message+' PicName: '+data.img);
})
});
Here my controller.php:
public function sendMessages()
{
JResponse::setHeader('Content-Type', 'application/json', true);
$app = JFactory::getApplication();
$input = $app->input;
$new-message = $input->getString('new-message', '', 'RAW');
$img = $_FILES['message-image-upload']["name"];
$img = JFile::makeSafe($img);
$results=array(
'new-message' => 'new-message',
'img' => $img
);
echo json_encode($results);
$app->close();
}
I got the datas / variables in the console log.
it is:
new-message: null,
img: null
trying to set contentType: false will give me an 500 error.
Thank you very much
That´s the info from my network
enter image description here
I figure something out.
It´s the URL in my ajax command.
When I am using a normal url like
url: 'upload.php'
that will work and then I can set the
contentType: false,
But this is not safety enought.
I just want to use this url
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
But then I got the error message that the view is not found. That´s very strange.

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.

input(file) and input (text) send with one ajax

html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.

Resources