We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to post file and key value pairs at the same time?

I am trying to post a file and regular key value pair data together using ajax. But it seems I can't get both through at the same time. How to achieve this?

var settingsData = new FormData();
var file = $("#background")[0].files[0];
settingsData.append("background", file, file.name);
settingsData.append("foo", "bar");

$.ajax({
    url: 'https://myurl.com',
    data: settingsData,
    contentType: false,
    processData: false,
    type: "POST"
})
.done(function (data) {
    console.log(data);
})
.fail(function (fail) {
    console.log('Error', fail);
});

If I have files I can go though them like this:

foreach ($this->request->getUploadedFiles() as $file){
    echo $file->getName(), " ", $file->getSize(), "\n";
}

But if I add key value pairs with the file I get nothing through. Why isn't FormData coming through so I could access it using json_decode(file_get_contents('php://input') ? Also $this->request->getPost("myVar") is empty.

First you need to close off the string for your URL. You're missing a closing single quote at the end of that string.

The reset looks OK, but you can troubleshoot ajax requests with Firebug or Chrome Dev tools in the console. Take a look and see what headers and params it is passing. Chances are, the controller is not even getting any data because of the string thing mentioned above.

First you need to close off the string for your URL. You're missing a closing single quote at the end of that string.

The reset looks OK, but you can troubleshoot ajax requests with Firebug or Chrome Dev tools in the console. Take a look and see what headers and params it is passing. Chances are, the controller is not even getting any data because of the string thing mentioned above.

My quotes are fine. I just missed it when I copy pasted. Ajax request is fine. It works perfectly with any other framework. Only Phalcon refuses to handle it properly.