2016-05-31 135 views
0

我正在使用插件datatable來顯示用戶列表。在這個列表中,我需要能夠上傳新文件。jQuery - 使用ajax的DataTables上傳文件

我想使用ajax嘗試發送數據到php。如果我發送值沒有問題,但我的PHP腳本工作,我無法從文件中獲取數據。

爲了上傳文件,我使用了我爲另一個工作正常的腳本編寫的腳本,所以我認爲這裏的問題是DataTable,它不能識別我的表單數據。

任何人都知道如何做到這一點?

FIDDLE

JS

$('#example .fileinput-upload-button').on('click', function(event) { 

    var td = $(this).closest("td"); 
    var parentTD = td.parent(); 

    var form = $(this).closest("form"); 
var url = "example/upload.php?type=photo" 
    var data = new FormData(form); 
    alert(form); 

    $.ajax({ 
    type: "POST", 
    url: url, 
    data: data, 
    mimeType: "multipart/form-data", 
    contentType: false, 
    cache: false, 
    dataType: "html", 
    processData: false, 
    success: function(data) { 

     alert(data); 
    } 
    }); 

PHP

$type = filter_input(INPUT_GET, "type"); 


$target_dir_header = $includesDir . "dashboard/resources/header_pic/"; 
$dataHeader = $_FILES['input7']; 
$dataHeader_ext = explode('/', $dataHeader['type']); 
$imageFileType_header = $dataHeader_ext[1]; 
$target_file_header = $target_dir_header . basename("header" . $imageFileType_header); 


echo $type . " - " . $imageFileType_header; 
+0

jsFiddle中沒有'form'標籤。 –

+0

是的,只是在輸入前 – SNos

+0

你是對的,對不起。見[這個答案](http://stackoverflow.com/questions/28872872/error-in-sending-form-file-with-form-using-ajax)。嘗試'var data = new FormData(); data.append('file',$('input [type = file]',form)[0] .files [0]);'而不是。 –

回答

0

jQuery代碼更改爲:

var td = $(this).closest("td"); 
var parentTD = td.parent(); 

var url = "example/upload.php?type=photo" 
var form = $(this).closest("form").get(0); 

    $.ajax({ 
    type: "POST", 
    url: url, 
    data: new FormData(form), 
    mimeType: "multipart/form-data", 
    contentType: false, 
    cache: false, 
    dataType: "html", 
    processData: false, 
    success: function(data) { 
    alert(data); 
    } 

}); 

你的問題解釋here

+0

謝謝..這是工作然而,php正在接收來自第一行的數據。如果我在其他行上選擇一張圖片,收到的數據總是從表 – SNos

+1

@SNos中的第一行開始,使用'$(this).closest(「form」)。get(0)'而不是'$('form' )獲得(0)'。 –

+0

非常感謝你。現在它工作正常 – SNos