2017-01-21 26 views
1

我想使用ajax發佈一些數據到服務器。我被困在上傳圖片,我不知道我的錯誤在哪裏。任何人都可以請建議我如何解決這個問題?ajax上傳表單到服務器使用php jquery

下面是我的腳本和php代碼。

$("#submit").click(function() { 

    var formData = new FormData(); 
    formData.append('file', $('input[type=file]')[0].files[0]); 

    var name = $("#first_name").val(); 
    var country = $("#country").val(); 
    var city = $("#city").val(); 

    $.ajax({ 

    url: 'personaliseService.php?name=' + name + '&country=' + country + '&city=' + city, 
    dataType: 'json', 
    processData: false, 
    contentType: false, 
    data: formData, 
    //data: new FormData(), // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
    success: function(response) { 
     console.log(response); 
    }, 
    error: function(error) { 
     alert("Yes"); 
     console.log(error); 
    } 

    }); 
}); 
<?php 

    include("config.php"); 

    $name = $_REQUEST['name']; 
    $country = $_REQUEST['country']; 
    $city = $_REQUEST['city']; 
    $image = $_FILES['image']['name']; 
    $sourcePath = $_FILES['image']['tmp_name']; 

    $targetPath = "uploads/".$_FILES['file']['name']; // Target path where file is to be stored 
    move_uploaded_file($sourcePath, $targetPath) ; // Moving Uploaded file 

    $sql = "INSERT into personalise (name, country, city, image) VALUES ('$name', '$country', '$city', '$image')"; 

    $sqlQuery = mysqli_query($conn, $sql); 

    if(mysqli_insert_id($conn) > 0){ 

     $insertValue = array("response" => "Data Inserted Successfully"); 
     echo '{"response": '.json_encode($insertValue).', "success": true}'; 

    }else{ 

     echo '{"response": '.json_encode($insertValue).', "success": false}'; 

    } 

?> 
+0

你的PHP代碼檢查'$ _FILES [「形象」]'但沒有提及'image'形式?爲什麼你的表單使用'dataType:'json''? –

+0

也看到http://stackoverflow.com/q/10492617/1072229 –

+0

是的,我明白刪除的dataType,但我怎麼能得到像參考請建議 –

回答

0

你必須使用相同的名稱來訪問文件中的PHP代碼,你在FORMDATA是「文件」提到。

希望你喜歡:)

相關問題