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
Related
I want to send the file data together with string data. I am able to send it from ajax to PHP. But in PHP I can not get correct string data from $_POST[] This doesn´t work. I don´t know how to get the correct string.
I got only initial alphabet from a string. No specific product that I want.
Here is ajax
var action = "product1="+myProduct1+"&product2="+product2;
var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', action);
$.ajax({
type: "POST",
url: "URL TO PHP",
data:form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
//Do something
},
});
PHP
$data=$_POST['data'];
$action=$_POST['action'];
$mydata = array("myStatus"=>"ok", "myMsg"=>$action['product1']);
echo json_encode($mydata);
UPDATE
I found one solution :
javascript script:
var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('product1',my_product1);
form_data.append('product2',my_product2);
PHP code :
$data=$_POST['data'];
$mydata = array("myStatus"=>"ok", "myMsg"=>$_POST['product2']);
echo json_encode($mydata);
I am a bit satisfy with this. If someone has another solution would be nice. Because I have lots of string data in this code. If I do manual like this....will look stupid. Unless this is the only solution I can do.
you may try like this,
var action = [
{
product : "product1",
},
{
product : "product2"
}];
var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', JSON.stringify(action));
$.ajax({
type: "POST",
url: "URL TO PHP",
data:form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
//Do something
},
});
and in php side,
$data = json_decode($post,true);
//print_r($data);
foreach ($data as $key => $value) {
echo $value['product'];echo "<br>";
}
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.
Please how can I send a whole number like twelve to php using ajax. I have been able to send string variables using both GET and POST methods successfully, but when it comes to numerical values it becomes a problem , I don't know why.below is my jQuery
function user_ajax_call(){
var data = $(".people_names").length;
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data:{data:data},
processData: false,
contentType: false,
cache:false,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And these are sample php lines
$limistart = $_POST['data'];
if(isset($limistart)){
echo $limistart;
}
You need to send them through: data.
You could do something like this in your data variable:
data = {
name_length : $(".people_names").length,
number : 12
};
And just pass it like this in your ajax:
function user_ajax_call(){
var data = {
name_length : $(".people_names").length,
number : 12
};
var more_loader = $("<img id='hiddenL' src='../ForePost/icons/spin.gif'/>");
$("#pple").append(more_loader);
$.ajax({
url: 'http://localhost/Forepost/mod/loadmore_data.php',
dataType: 'text',
type: 'POST',
data: data,
success: function(returndata){
$("#pple").append(returndata);
more_loader.hide();
},
error: function () {
}
});
}
And in your server side access it like :
$_POST['name_length']
$_POST['number']
If you change the value of contentType key it should work correctly.
So change this:
contentType: false
to:
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
EDIT:
and change the line:
processData: false
to:
processData: true
I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})