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']);
Related
I've a portal in which I'm recording user audio and I am getting a blob URL and now I want to store this blob url as a file in my database. Can anyone help me with this.
This is my js code
$('#upload-read-aloud').on('submit',function(e){
e.preventDefault();
$.ajax({
type : 'GET',
cache : false,
data : {audioUrl:audioUrl},
url : '../upload-read-aloud-test',
success:function(response){
alert(response)
}
})
})
And this is my controller code
$url = $req->audioUrl;
$upload_dir = public_path()."/assets/";
$audio= $url;
$audio= str_replace('data:audio/wav;base64,', '', $audio);
$audio = str_replace(' ', '+', $audio);
$data = base64_decode($audio);
$file = $upload_dir . time() . ".wav";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
audioUrl is the Blob url which I'm passing in my route. The file is saving into the database but the file is empty.
As I see you use jQuery.
So, first of all DO NOT use GET request to upload data to server, use POST request instead. And send your blob as a file. Look at - https://stackoverflow.com/a/34340245/2585154
var s = 'some string data';
var filename = 'foobar.txt';
var formData = new FormData();
formData.append('file', new File([new Blob([s])], filename));
formData.append('another-form-field', 'some value');
$.ajax({
url: '/upload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function () {
console.log('ok');
},
error: function () {
console.log('err'); // replace with proper error handling
}
});
Replace /upload with path to your API method, e.g.: ../upload-read-aloud-test, replace var s = 'some string data'; with your blob data and replace var filename = 'foobar.txt'; with any meaningful filename.
Or if you want to upload file from input, look at - jQuery AJAX file upload PHP
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
Replace upload.php with path to your API method, e.g.: ../upload-read-aloud-test, replace #sortpicture with your input id.
And then access your uploaded file in Laravel:
$file = $req->file('file');
dump($file);
trying to upload all images from a folder
destination folder on server side is test
destination format for images is uniqid().jpg
problem - seems resulting array on server side is empty
<input type='file' class='inpfile' id='inpfo' webkitdirectory='' directory='' multiple='true'>
var inpfo = $('#inpfo');
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
fd.append('flist', flist);
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
contentType: 'multipart/form-data',
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
upload.php
$arr = $_FILES['flist']; //seems this is an empty array
foreach($arr as $el){
$tempname = $el['tmp_name'];
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}
You are passing a FileList object fd.append which is incorrect you have to loop through the list and add each file individually.
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
for (let i = 0; i < flist.length; i++){
fd.append('flist[]', flist[i]); // add [] to denote array
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
You're using the array of files incorrect, see here
$arr = $_FILES['flist'];
foreach($arr['tmp_name'] as $tempname){
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}
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 want to send FirstName, LastName and Image through Ajax Call to PHP. I am able to send the data without image, and I am able to send the image without text using formdata but the problem is I am not able to do both at a time. Kindly check my code what I am doing wrong:
<script>
function createBasicInfo() {
// For Image Send
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
// For Text Send
var data = {
'firstname' : jQuery('#firstname').val(),
'lastname' : jQuery('#lastname').val(),
};
**//Here Is the Problem, I am not able to append the data with Text**
formdata.append(data);
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
In above code if I comment
//formdata.append(data); // Then only image will send to php
And If I use in Ajax Call
data: data, // Then only FirstName & LastName will send to php without Image
I am not able to send text data and image both at the same time to php file.
Any idea or suggestion would be welcome.
You could just do this insted of formdata.append(data):
formdata.firstname = jQuery('#firstname').val();
formdata.lastname = jQuery('#lastname').val();
Just append your firstname and lastname into formdata. Then send full formdata.
<script>
function createBasicInfo() {
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
formdata.append('firstname', jQuery('#firstname').val());
formdata.append('lastname', jQuery('#lastname').val());
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
// ...
// ...
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
I am using the plugin datatable to show a list of users. In this list I need to be able to upload new files.
I am trying to use ajax to try to send data to php. If I send value there is not problem my php script works however, I cannot get the data from the files.
In order to upload the files I am using the same script that I have written for another project which is working fine, so I think here the problem is DataTable that do not recognise my form data.
Anyone knows how to achieve this?
FIDDLE
JS
$('#example .fileinput-upload-button').on('click', function(event) {
var td = $(this).closest("td");
var parentTD = td.parent();
var form = $(this).closest("form");
var url = "example/upload.php?type=photo"
var data = new FormData(form);
alert(form);
$.ajax({
type: "POST",
url: url,
data: data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType: "html",
processData: false,
success: function(data) {
alert(data);
}
});
PHP
$type = filter_input(INPUT_GET, "type");
$target_dir_header = $includesDir . "dashboard/resources/header_pic/";
$dataHeader = $_FILES['input7'];
$dataHeader_ext = explode('/', $dataHeader['type']);
$imageFileType_header = $dataHeader_ext[1];
$target_file_header = $target_dir_header . basename("header" . $imageFileType_header);
echo $type . " - " . $imageFileType_header;
Change your JQuery code to:
var td = $(this).closest("td");
var parentTD = td.parent();
var url = "example/upload.php?type=photo"
var form = $(this).closest("form").get(0);
$.ajax({
type: "POST",
url: url,
data: new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType: "html",
processData: false,
success: function(data) {
alert(data);
}
});
Your question explains here