5

I am trying to submit a full form for server side processing using jQuery. The form contains various fields including a file upload option. I am trying to use FormData to do this as I don't care about browsers that don't support it at the moment.

I have the following (simplified) jQuery code:

$("#create_event_form").submit(function(event) {
    event.preventDefault();

    var formData = new FormData($(this));

    $.post(
        "create_entity.php",
        { formData: formData },
        function(data) {
            var response = jQuery.parseJSON(data);
            if(response.code == "success") {
                alert("Success!");
            } else if(response.code == "failure") {
                alert(response.err);
            }
        }
    );
});

And my server side looks like the following:

<?php
require_once('includes/database.php');


$dbh = db_connect();

$response = array();
if($_SERVER['REQUEST_METHOD'] == "POST") {
    // do some other stuff...       

    // upload entity picture and update database
    $url = $_FILES['entity_pic']['name'];
    if($url != "") {
        if($type == "user") {
            $pic_loc = "images/profiles/";
        } else if($type == "chapter") {
            $pic_loc = "images/chapters/";
        } else if($type == "group") {
            $pic_loc = "images/groups/";
        } else if($type == "event") {
            $pic_loc = "images/events/";
        }
        // upload the picture if it's not already uploaded
        if(!file_exists($pic_loc . $_FILES['entity_pic']['name'])) {
            move_uploaded_file($_FILES['entity_pic']['tmp_name'], $pic_loc . $url);
        }
        $image_query = "INSERT INTO image (entity_id, url, type) VALUES (:entity_id, :url, :type);";
        $image_query_stmt = $dbh->prepare($image_query);
        $image_query_stmt->bindParam(":entity_id", $entity_id);
        $image_query_stmt->bindParam(":url", $url);
        $image_query_stmt->bindValue(":type", $type);
        if(!$image_query_stmt->execute()) {
            die(print_r($image_query_stmt->errorInfo()));
        }
    }


    echo json_encode($response);

}

?>

And some relevant HTML:

<form id="create_event_form" action="create_entity.php" method="POST" enctype='multipart/form-data'>
    <input type="file" name="entity_pic" value="Insert Photo" />
    <!-- other inputs -->
</form>

Right now I get an Illegal invocation error, presumably on my initialization of my FormData object. I've been searching forever of example of how to do this with jQuery and am coming up empty. Also, I want to clarify that my server side code will work. When I pass the formData as "formData" to my PHP script, how do I access the fields in it? Would it be "$_POST['formData']['field_name']" or just $_POST['field_name'] or something else entirely?

Thanks for any help.

3
  • Similar to this SO question perhaps? Dec 6, 2012 at 18:43
  • The only problem is that I have a ton of other values in the form I want to submit. Do I have to do an append statement for each one? I had hoped I could initialize the FormData object with a form reference...
    – Jon Rubins
    Dec 6, 2012 at 18:46
  • Also, I need help understanding how to process the submitted FormData object in my server side code
    – Jon Rubins
    Dec 6, 2012 at 18:46

2 Answers 2

15

FormData takes a form element in its constructor not a jQuery object - var formData = new FormData(this);

You have set some options for jQuery ajax to handle the formdata object so you should use $.ajax instead of $.post, also pass the formdata itself as the data.

$.ajax({
  url: "create_entity.php",
  data: formData,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data) {
        var response = jQuery.parseJSON(data);
        if(response.code == "success") {
            alert("Success!");
        } else if(response.code == "failure") {
            alert(response.err);
        }
    }
});
1

To answer your last question, I believe it would be $_POST['field_name']. Check out this post for some information on the implementation you're looking for: Sending multipart/formdata with jQuery.ajax

Hope this helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.