我的PHP文件的AJAX POST请求有点麻烦

时间:2016-06-20 00:30:07

标签: javascript php mysql ajax

我正在尝试使用Ajax向我的MYSQL数据库提供数据,但是,由于某些原因,我的PHP文件没有读取我发布到文件的JSON数组。在数组中我还有一个文件来存储我的服务器和我的数据库上的图像。

Javascript文件

    $(document).ready(function(){

// Give Data to PHP

       // process the form
               $('form').submit(function(event) {

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)

    //formData.append('tax_file', $('input[type=file]')[0].files[0]



    var img = $('input[name=img]').prop('files')[0];
    var name = img.name,
        tmp = img.tmp_name,
        size = img.size,
        form = $('input[name=form-submit]').val(),
        myName = $('input[name=my-name]').val(),
        desc = $('input[name=description]').val();

        // document.write(name + tmp + size);



    var formData = {
        'form-submit' :  form,
        'my-name'     :  myName,
        'description' :  desc,
        'img'         :  name,
        'tmp_name'    :  tmp,
        'size'        :  size
    };

    // document.write(JSON.stringify(formData));

    console.log(formData);

    // process the form
    $.ajax({
        url         : 'insert-bio.php', // the url where we want to POST
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        data        : formData, // our data object
        processData : false,
        contentType : false,
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true
    })

        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

我的PHP文件

      include('../db.php');

$conn = new Database();

echo explode(",", $_POST['data']);

if(isset($_POST['form-submit'])){
 // text data


 $name = strip_tags($_POST['my-name']);
 $desc = strip_tags($_POST['description']);


 // picture stuff
 $file = rand(1000,100000)."-".$_FILES['img']['name'];
 $file_loc = $_FILES['img']['tmp_name'];
 $file_size = $_FILES['img']['size'];
 $file_type = $_FILES['img']['type'];

 // folder for profile pic
 $folder = "bio-pic/";

 // new file size in KB
 $new_size = $file_size/1024;  

 // make file name in lower case
 $new_file_name = strtolower($file);

 // final pic file
 $final_file=str_replace(' ','-',$new_file_name);

 // mysql query for form data
    if(move_uploaded_file($file_loc,$folder.$final_file)){
        $sql="INSERT INTO bio(img, name, description) VALUES('$final_file', '$name', '$desc')";
        $conn->query($sql);
    }   
} else  {
    echo "Need data";
}

$query = $conn->query("SELECT * FROM bio");
    $results=$query->fetchAll(PDO::FETCH_ASSOC);
    $parse_bio_json = json_encode($results);

    file_put_contents('bio-DATA.json', $parse_bio_json);
    echo $parse_bio_json;

控制台显示我已经与我的PHP文件联系,但它根本没有读取任何数据。

PHP文件中的错误:

Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8
Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 ArrayNeed data[]

1 个答案:

答案 0 :(得分:0)

我当天回到了同样的问题。经过大量研究后,我发现 JSON不能拥有包含文件值的属性。但是,您可以按照此示例操作。它对我很有用。希望它有所帮助:)

$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);
alert(form_data);                             
$.ajax({
            url: 'upload.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); // display response from the PHP script, if any
            }
 });
});

<强> PHP

<?php

if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

信用转到 - &gt; jQuery AJAX file upload PHP