I'm trying to send an image to an ajax handler via ajax. If I console.log the variable ìmage I am sending, it looks fine. As of now I am sending it to the handler and just trying to echo it back. But I get a blank response. I am sending the image: formData inside an object which I hope is ok.
Ajax:
var form_data = new FormData();
var image = $('#newImage').prop('files')[0];
var image_name = image.name;
var image_extension = image.name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension, ['gif', 'jpg', 'JPG', 'pjpeg', 'x-png', 'png', 'PNG', 'jpeg']) == -1) {
alert("Invalid Image File Type")
}
var image_size = image.size;
if(image_size > 700000) {
alert("Image too big!");
} else {
form_data.append('file', image);
}
let data = {
action: 'NewEventExhibition',
name: name,
description: description,
notes: notes,
status: status,
slug: slug,
start_date: start_date,
end_date: end_date,
event_code: '<?=$code?>',
image: form_data
};
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false,
mimeType: 'multipart/form-data',
success: function(response) {
alert(response);
},
fail: function(response) {
console.log(response);
}
})
}
});
Handler
if($_FILES['file']['name'] != '') {
$test = explode(".", $_FILES['file']['name']);
$extension = end($test);
$name = rand(100, 999).'.'.$extension;
$location = "/assets/images/".$name."";
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo $location;
}
```
That's not how you send a FormData object with ajax. The form_data object should be the thing that you send, not it being part of a bigger object.
I would recommend you to append all the fields of the object data to the form_data and send it.
Something like the following:
form_data.append('action', 'NewEventExhibition');
form_data.append('name', name);
form_data.append('description', description);
form_data.append('notes', notes);
form_data.append('status', status);
form_data.append('slug', slug);
form_data.append('start_date', start_date);
form_data.append('end_date', end_date);
form_data.append('event_code', '<?=$code?>');
instead of let data = { .... }.
Then you can send it with
$.ajax({
url: '/modules/ajax/ajax_handler.php',
type: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: 'multipart/form-data',
success: function(response) {
alert(response);
},
fail: function(response) {
console.log(response);
}
});
Please note the data: form_data.
Related
When trying to upload a file CSV / Excel file and receiving it in an ajax request, it's not working as expected.
I used a formdata object to upload the files like such:
const formData = new FormData()
formData.append('file', file)
//upload the file to the server
Api.makeRequest('uploadFromFile', {
processData: false,
contentType: false,
enctype: 'multipart/form-data',
cache: false,
data: formData,
complete: function (xhr) {
if(xhr.status === 201 || xhr.status === 200){
console.log(xhr.responseJSON)
}else {
alert('error')
console.error(xhr.responseJSON)
}
}
})
As I read from the documentation, you have to extract it like such:
$file = $request ->file('file_key')
When using this syntax, I get an error, and Laravel can't extract the file:
public function uploadFromFile(Request $request){
if($request->hasFile('file')){
$file = $request->file('file');
return $file;
}else{
return response()->json(['error' => 'No file uploaded'], 400);
}
However, it works fine when I use the regular request->has() function. A return type is just an object. What am I doing wrong since I can't get the file in the correct format?
//This works, getting some data but not a proper file object
public function uploadFromFile(Request $request){
if($request->has('file')){
$file = $request->get('file');
return $file;
}else{
return response()->json(['error' => 'No file uploaded'], 400);
}
<script>
var droppedFiles='';
//input file change event to call this function
function FileUpload(e)
{
droppedFiles = e.target.files || e.dataTransfer.files;
}
$('#FrmId').on('submit', function (e) {
var $form = $('#FrmId');
var $input = $form.find('input[type="file"]');
var form_data = new FormData($('#FrmId')[0]);
if (droppedFiles)
{
$.each( droppedFiles, function(i, file) {
form_data.append( $input.attr('name'), file );
});
}
$.ajax({
type: "POST",
enctype: "multipart/form-data",
url: "url",
data: form_data,
contentType: false,
cache: false,
processData: false,
}).done(function (data) {
}).fail(function () {
});
return false;
});
</script>
I want to send data using an Ajax request to PHP.
I have the following data in my formData variable:
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
Printing the form entries gives me this:
I do the request like this:
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
In post.php I print the recieved data:
print_r("First name: " . $_POST["fname"] . PHP_EOL);
print_r("Last name: " . $_POST["lname"] . PHP_EOL);
print_r("Email: " . $_POST["email"] . PHP_EOL);
print_r("Data: " . $_POST["data"] . PHP_EOL);
For some reason it does not receive the 'data' entry in the $_POST variable. I get the following notice: "Notice: Undefined index: data"
Why does that happen? Could I somehow send the blob information?
As requested, the whole code. (inputFname, inputLname and inputEmail are not null. The code is situated inside a button onclick event method.
let evtTgt = e.target;
const container = evtTgt.parentNode;
const audioElement = container.getElementsByTagName("audio")[0];
const audioURL = audioElement.src;
let newBlob = await fetch(audioURL).then(result => result.blob());
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
for (var key of formData.entries()) {
console.log(key[1]);
}
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
All this time I was looking for the blob contents inside the $_POST variable. I should have looked in the $_FILES variable instead!
I managed to get the file contents by calling this inside the php script:
$fileinfo = file_get_contents($_FILES['data']['tmp_name']);
I've been trying to upload a file using the Google Drive API but I'm facing this issue and I can't seem to find the solution. When uploading an image, it uploads a corrupted file of size 1kb with correct metadata and while uploading text files, it uploads a text file with [object file] as data and not the original data of the file.
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var control = document.getElementById("csv");
var files = control.files;
var dat=files[0];
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
contentType: false,
data: "\n--foo_bar_baz\ \nContent-Type: application/json; charset=UTF-8\ \n\n{ 'name': '"+dat.name+"' }\ \n--foo_bar_baz\ \nContent-Type: "+dat.type+"\ \nContent-Transfer-Encoding: base64\ \n\n"+dat+"\ \n--foo_bar_baz--\ ",
headers: {
"Authorization":"Bearer <?php echo $result["access_token"]; ?>",
"Content-Type": "multipart/related; boundary=foo_bar_baz",
"Content-Length": formData.length
},
async: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
var res = JSON.stringify(response);
console.log("S: "+res);
},
error: function(response) {
var res = JSON.stringify(response);
console.log("E: "+res);
}
});
return false;
});
How about this answer? Please think of this as just one of several possible answers.
Modification points:
You are trying to upload the file as base64. But in your script, dat is not base64.
In this case, I used FileReader.
Please remove \ of \ \n in "\n--foo_bar_baz\ \nContent-Type: application/json; charset=UTF-8\ \n\n{ 'name': '"+dat.name+"' }\ \n--foo_bar_baz\ \nContent-Type: "+dat.type+"\ \nContent-Transfer-Encoding: base64\ \n\n"+dat+"\ \n--foo_bar_baz--\ ",.
When above points are reflected to your script, it becomes as follows.
Modified script:
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var control = document.getElementById("csv");
var files = control.files;
var dat = files[0];
var f = new FileReader(); // Added
f.onload = function(){ // Added
const base64Data = this.result.split(",")[1]; // Added
$.ajax({
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
type: 'POST',
contentType: false,
data: "\n--foo_bar_baz\nContent-Type: application/json; charset=UTF-8\n\n{'name': '"+dat.name+"'}\n--foo_bar_baz\nContent-Type: "+dat.type+"\nContent-Transfer-Encoding: base64\n\n"+base64Data+"\n--foo_bar_baz--\n", // Modified
headers: {
"Authorization": "Bearer <?php echo $result["access_token"]; ?>",
"Content-Type": "multipart/related; boundary=foo_bar_baz",
"Content-Length": formData.length
},
async: false,
cache: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
var res = JSON.stringify(response);
console.log("S: "+res);
},
error: function(response) {
var res = JSON.stringify(response);
console.log("E: "+res);
}
});
}
f.readAsDataURL(dat); // Added
return false;
});
Note:
When uploadType=multipart is used, the maximum file size is 5 MB. Please be careful this. Ref
If this was not the direct solution of your issue, I apologize.
I'd like to pass a PHP session variable (called 'profileid') using FormData and AJAX. I thought this below would work, it did not. Why?
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
imageData.append('profileid', <?php echo $_SESSION['profileid'];?>);
//Make ajax call here:
$.ajax({
url: '/upload-image-results-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: imageData,
//leaving out the rest as it doesn't pertain
You could add the profileid in the $.ajax URL parameter instead of adding it in FormData:
$(document).ready(function (e) {
$('#uploadImageForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "/upload-image-results-ajax.php?profileid=<?= $_SESSION['profileid']; ?>",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}));
$('#uploadImage').on("change", function() {
$("#uploadImageForm").submit();
});
});
Don't forget to place session_start(); at the beginning of your code.
I have read in other post on SO, similar to what is happening to me, but I still can not get the solution
$('#edit-continue').on('click', function(e) {
e.preventDefault();
var photo = new FormData(); <-----
jQuery.each(jQuery('#photo')[0].files, function(i, file) {<----- SO suggest for file upload
photo.append('file-' + i, file); <-----
});
$.ajax({
type: "POST",
url: "/templates/staycation/common/edit-profile.php",
data: {
id: $('#id').val(),
email: $('#email').val(),
birthday: $('#birthday').val(),
gender: $("input[name='gender']:checked").val(),
photo: photo,
},
success: function(data) {
console.log('pass');
console.log(data);
},
error: function(data) {
console.log('not pass');
console.log(data);
},
cache: false,
contentType: false,
processData: false, <------ i think my error is here
});
if i leave processData: false, , the post arrives empty, by making echo of my array, all data is empty, in the other case, if I comment, the console throws Uncaught TypeError: Illegal invocation
I need to do is send the values entered by the user such as "email", "gender", ... and profile picture, to make an update to the database and to save the image to a folder
this is what working perfectly for me
// formData will wrap all files and content of form
var formData=new FormData($('#formId')[0]);
// you can add more data ot formData after this to
$.ajax({
url : 'upload.php',
type : 'post',
data : formData,
processData:false,
contentType:false,
success : function(e)
{
alert('uploaded successfully');
},
error : function()
{
alert('hello from here');
}
});