I need to send some data using ajax and FormData, because I want to send a file and some other parameters. The way I usually send data is this:
$.ajax({
On my end, I stringify my nested parameters and parse them on the other end.
For instance, if I want to pass:
{"sthing":
{"sthing":"sthing"},
{"picture":
{"legend":"great legend"},
{"file":"great_picture.jpg"}
}
}
Then I do:
// On the client side
const nestedParams = {"sthing":
{"sthing":"sthing"},
{"picture":
{"legend":"great legend"}
}
};
const pictureFile = document.querySelector('input[type="file"]')[0];
const formDataInstance = new FormData;
formDataInstance.append("nested_params": JSON.stringify(nested_params);
formDataInstance.append("file": document.querySelector('input[type="file"]')[0]);
// On the server side
params["nested_params"] = JSON.parse(params["nested_params"]);
params["nested_params"]["sthing"]["picture"]["file"] = params["file"];