Ajax file upload in Wordpress - can't pass FormData

前端 未结 5 861
失恋的感觉
失恋的感觉 2021-01-02 07:13

I\'ve made a script which uses $.ajax and FormData to pass two form objects to PHP. One form object is a text and the other is a file. It worked well as a stand-alone script

5条回答
  •  生来不讨喜
    2021-01-02 08:07

    Works whith any input(one or many simple or multiple), textarea, select in your form (WP 5.0.3)

        $('#form').submit(function(e) {
            e.preventDefault();
    
            var form = $(this);
            var formdata = (window.FormData) ? new FormData(form[0]) : null;
            var data = (formdata !== null) ? formdata : form.serialize();
    
            formdata.append("action", "fiu_upload_file");
    
            $.ajax({
                type: 'POST',
                url: fiuajax.ajaxurl,
                contentType: false,
                processData: false,
                dataType: 'JSON',
                status: 200,
                data: formdata,
                success: function(data){                    
                    if(data.error == 'true') {
                        $('.msg').html(data.true);                          
                    }
                    else {
                        $('.msg').html(data.false); 
                        // your code if you want an action ...                                                                          
                    };
                }
            });
        });
    

    and php for only the files

        foreach ($_FILES as $file) :
            if($file['error'] == UPLOAD_ERR_NO_FILE) :
                continue;
            endif;
    
            $valid_ext = array( 'jpg' , 'jpeg' , 'png' , 'doc' , 'docx' , 'pdf' , 'xls' , 'xlsx');
            $extension_upload = strtolower(  substr(  strrchr($file['name'], '.')  ,1)  );
            if ( in_array($extension_upload,$valid_ext) ) :
                $name_upload = uniqid() . $file['name'];
                $url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
                wp_mkdir_p($url_insert);
                $name_insert = trailingslashit($url_insert) . $name_upload;
                $action = move_uploaded_file($file['tmp_name'],$name_insert);
                $msg_true = 'Upload ok ';
            else :
                $msg_error = 'Upload error';
            endif;
        endforeach;
    
        $result = !isset($msg_error);
        $msg = array();
    
        if($result) :
            $msg['error'] = 'true';
            $msg['true'] = $msg_true;
        else :
            $msg['error'] = 'false';
            $msg['false'] = $msg_error;
        endif;
    
    
    
        header('Content-Type: application/json');
        echo json_encode($msg);
    
        
    

提交回复
热议问题