0

I have a regular multipart/form-data that has some fields and 1 fileinput. I then send it to my php via:

$(document).on('submit', '#create-event-form', function(){
        var form_data = JSON.stringify($(this).serializeObject());

        $.ajax({
            url: "../api/event/create.php",
            type : "POST",
            contentType : 'application/json',
            data : form_data,
            success : function(result) {
                showEvents();
            },
            error: function(xhr, resp, text) {
                // show error to console
                console.log(xhr, resp, text);
            }
        });

        return false;
    });

This is, in turn received and saved to my db using:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate event object
include_once '../objects/event.php';

$database = new Database();
$db = $database->getConnection();

$event = new Event($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

$now = new DateTime();
$timestamp = $now->getTimestamp();

$file = $_FILES['painting']['name'];
$extension = end(explode(".", $file));

$location = "painting/$timestamp" . $file . $extension;

//move_uploaded_file($_FILES['painting']['tmp_name'], $location);

// set event property values
$event->name = $data->name;
$event->max = $data->max;
$event->painting = $location;

// create the event
if($event->create()){
    $arr = array('message' => 'Evt created.');
    echo json_encode($arr);
}else{
    $arr = array('message' => 'Error creating the event.');
    echo json_encode($arr);
}

Now, if I only pass the form_data I can successfully save everything, however, the file never reaches the PHP because I can't use php://input with multipart/form-data. I'm aware of that, so I'm looking for some way around it.

I've tried to send the file as part of the data:{key:value} pair on the js side but I can't get that to work. I've been at this for several hours now but I can't fathom how to do it (hence why move_uploaded_fileis commented, right now there's nothing in $_FILES so it fails).

Can anyone suggest a way for me to do this, please?

1 Answers1

0

HTML5 introduces FormData class that can be used to file upload with ajax. https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

I think you would be nice to pay attention to different plug-ins. Like:

And to combine your logic with the work of something like that

Also I think this answer can help you how to do file upload using jquery serialization .

Replik
  • 54
  • 4