$_FILES is always null

I am trying to get the name of the file that has been selected for upload through ajax and form data method. I am currently working in WordPress and below is my code. I want that name of the selected file should be returned through the function. Null is returned in $_FILES and also please how I can upload this file but the first hurdle is that my $_FILES['file'] is always null. Thanks

Html Upload form

Read More
[testupload]
<form id="test" action="" method="post" enctype='multipart/form-data'>

<input id="files" type="file" name="file" style="margin-top:12px;">

<input name="testupload" type="submit" value="upload"/>
</form>
<div id="result"></div>

Ajax code

jQuery(function ($) {
    $("#test").submit(function (e) { //form is intercepted
    e.preventDefault();
var sent = $(this).serializeArray();

var sentdata = $(this).serializeArray();

        //$("#result").html("zeeshan aslam durrani");
        alert("jquery file is connected");
        //serialize the form which contains secretcode
                var file = jQuery(document).find('input[type="file"]');
        formData = new FormData();
        var image = $('#files')[0].files[0];
        formData.append("file",image);
        alert(formData)

        //Add the additional param to the data        
        sent.push({
            name: 'action',
            value: 'testfunction',
            data: formData
        })

        //set sentdata as the data to be sent
        $.post(yes.ajaxurl, sent, function (res) { //start of funciton
            //$("#myresult").append(res.l);
            $("#result").html("");
            $("#result").html(res);
            alert(res);
 //$.parseJSON(data);
            return false;
        } //end of function
        ,
        'json'); //set the dataType as json, so you will get the parsed data in the callback
    });  // submit end here

    });

PHP code

//test upload

    add_action( 'wp_ajax_testfunction', 'testfunction' );
add_action( 'wp_ajax_nopriv_testfunction', 'testfunction');

add_shortcode('testupload','testupload');

function testupload()
{

// register & enqueue a javascript file called globals.js
wp_register_script( 'testscript', get_stylesheet_directory_uri() . "/js/ajaxinsert.js", array( 'jquery' ) ); 
wp_enqueue_script( 'testscript');

// use wp_localize_script to pass PHP variables into javascript
wp_localize_script( 'testscript', 'yes', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

}

function testfunction()
{
//echo json_encode("My name is khan");
echo json_encode($_FILES['file']);
die();  
}

Always null is returned in $_FILES … kindly help and thanks

Related posts

Leave a Reply