Sending JSON object along with file using FormData in ajax call and accessing json object in PHP
I am trying to send a json object along with a file in an ajax call as follows
Javascript
$('#btn').on('click', function(){
var file_data = $('#imgFile').prop('files')[0];
var form_data = new FormData();
let jsonObj = {
'label1':'value1'
};
form_data.append('file', file_data);
form_data.append('json', jsonObj);//json object which I am trying to send
$.ajax({
url: 'uploader.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
console.log(php_script_response);
}
});
});
and in PHP I can get the file sent in the ajax call, but I don't know how to access the json object sent along with this file
PHP
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
$file_ext=strtolower(end(explode('.',$_FILES['file']['name'])));
move_uploaded_file($_FILES['file']['tmp_name'], 'uploadedFiles/1.' . $file_ext);
echo $_POST['json'];
}
please let me know how to restore json object in php
source to share
First, note that you can only add binary data or a string through the method FormData.append()
. Providing an object as you mean that there will be a call on it toString()
, so the value will actually become "[object Object]"
.
To fix this, you need to manually create JSON.stringify
an object before you can use append()
it:
let obj = {
'label1':'value1'
};
form_data.append('file', file_data);
form_data.append('json', JSON.stringify(obj));
Then, in your PHP, you can deserialize the JSON with json_decode()
.
However, it would be much easier to just add values to the object FormData
directly. This way you don't have to manually serialize / deserialize anything:
form_data.append('file', file_data);
form_data.append('label1', 'value1');
form_data.append('foo', 'bar');
Then in your PHP:
var label = $_POST['label'];
var foo = $_POST['foo'];
source to share