Why am I not able to grab the file selected in my <input type=”file”>?

I’m developing a WordPress theme and I have a PHP function that is supposed to handle and asynchronous request that gives the server both JSON and an image. My form (for readability, stripped of a bunch of inner HTML) looks like

       <form method="POST" action="member-update"  enctype="multipart/form-data" id="member-form">
 9">
            <input type="text" name="fullname" value=""> 
            <input type="text" name="title" value="">
            <textarea rows="4" name="bio" form="member-form"></textarea> 
            <input type="text" name="sord" value=""> 
            <input type="file" name="pic">
            <input type="hidden" name="memberAction" value="" />
    </form>

and my JavaScript for making the AJAX request is

Read More
        jQuery('.member-update-button').click( function() {
            var parentForm = jQuery(this).closest('form');
            var postData = parentForm.serializeArray();
            jQuery.post( ajaxurl,
                        {'action': 'member_update', 'formStuff' : postData},
                        function(response) { alert('Got this from the server: ' + response); }
                       );
        });

and my PHP function that, through a WordPress hook, handles the request starts out like

function member_update ( )
{
    // there must be a more elegant way of getting those values out .... 
    $name = $_POST['formStuff'][0]['value'];
    $title = $_POST['formStuff'][1]['value'];
    $bio = $_POST['formStuff'][2]['value'];
    $sord = $_POST['formStuff'][3]['value'];


    $targetFileName = basename($_FILES['pic']['name']);
    $targetFileNameAndPath = 'assets/' . $targetFileName;

I’m getting values out of the $_POST['formStuff'] array, but I am getting nothing for the $_FILES['pic']['name']. Any idea what I’m doing wrong?

Related posts

1 comment

  1. You need to use an instance of FormData.
    Make following changes in your code.

    Add id attribute in your html

    <input type="file" name="pic" id="pic">
    

    Changes in js code

    jQuery('.member-update-button').click( function() {
       formdata = new FormData();
       formdata.append( 'action', 'member_update' );
    
       jQuery.each(jQuery('#pic')[0].files, function(i, file) {
           formdata.append('file_to_upload', file);
       });
    
       jQuery.post( ajaxurl, formdata,function(response) {
          alert('Got this from the server: ' + response); 
       });
    });
    

    Finally changes in php function

    function member_update()
    {
       $file = $_FILES['file_to_upload']['tmp_name'];
    }
    

Comments are closed.