2017-01-21 27 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是“文件”提到。

希望你喜欢:)

相关问题