Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending JSON object along with file using FormData in ajax call and accessing the json object in PHP

I am trying to send json object along with a file in 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 am able to retrieve the file sent in ajax call successfully but I dont know how to access the json object sent along with that 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 retrive the json object in php

like image 602
Summy Sumanth Avatar asked May 17 '17 13:05

Summy Sumanth


People also ask

How pass JSON object in post request in AJAX?

ajax({ url: , type: "POST", data: {students: JSON. stringify(jsonObjects) }, dataType: "json", beforeSend: function(x) { if (x && x. overrideMimeType) { x. overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { //Write your code here } });

Can we send JSON in form data?

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

Can you use JSON with AJAX?

According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.

Can we send object in formData?

Yes you can, you can append to formData objects.


1 Answers

Firstly, note that you can only append binary data or a string through the FormData.append() method. Providing an object as you are means that toString() will be called on it, so the value will actually become "[object Object]".

To fix this you'll need to manually JSON.stringify the object before you 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 deserialise the JSON using json_decode().

However, it would be much simpler to just append the values to the FormData object directly. That way you don't need 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'];
like image 147
Rory McCrossan Avatar answered Oct 07 '22 19:10

Rory McCrossan