使用php和jquery / ajax上传文件并将数据插入数据库

时间:2018-05-10 13:21:33

标签: php jquery ajax

您好我正在尝试上传图片并将数据插入项目表(phpmyadmin)如果我不使用ajax,但是当我尝试使用ajax上传它没有工作时,它可以正常工作

这是我的html5脚本

<form id="InsertItemTodatabase" enctype="multipart/form-data" action="requests/newItem.php" method="post" class="add-new-item-form-form">

                    <div class="form-group">
                        <input type="text" name="itemName" placeholder="Item name" class="form-control" id="itemNameJs">
                    </div>

                    <div class="form-group">
                        <input type="text" name="itemDesc" placeholder="Item Description" class="form-control" id="itemDescJs">
                    </div>

                    <div class="form-group">
                        <input type="text" name="itemPrice" placeholder="Item Price" class="form-control" id="itemPriceJs">
                    </div>


                    <div class="form-group">
                        <?php $fetch = fetchData( '*', 'category', '' , '', '', $fetch="fetchAll" ); ?>

                        <select class="form-control" name="category" id="itemCatJs">
                            <option value="0">Select Category</option>
                            <?php 

                                foreach ($fetch as $data) {
                                    echo '<option value="' . $data[ 'cat_id' ] . '">' . $data[ 'cat_name' ] . '</option>';
                                }

                            ?>

                        </select>

                    </div>


                    <div class="form-group">
                        <input type="text" name="itemAmount" placeholder="Amount" class="form-control" id="itemAmountJs">
                    </div>

                    <div class="form-group">
                        <label for="uploadItemPic" class="btn btn-primary">Upload Item Picture</label>
                        <input type="file" id="uploadItemPic" name="itemPic" class="form-control">
                    </div>

                    <div class="form-group">
                        <button type="submit" name="submitAddItemForm" id="submitNow">
                            <i class="ti-plus"></i>
                            Add Item
                        </button>
                    </div>

                </form><!-- /.add-new-item-form-form -->

这是我用于上传数据的jQuery / Ajax脚本。

$(document).on( 'submit', '#InsertItemTodatabase', function(e){
    e.preventDefault();

    var file_data = $('#uploadItemPic').prop('files')[0],
        name      = $( '#itemNameJs' ).val(),
        desc      = $( '#itemDescJs' ).val(),
        price     = $( '#itemPriceJs' ).val(),
        cat       = $( '#itemCatJs option:selected' ).val(),
        amount    = $( '#itemAmountJs' ).val(),
        image     = $( '#uploadItemPic' ).val();

        var file = new FormData();
        file.append('file',$('#uploadItemPic')[0].files[0]);

    var ajaxUrl = $(this).attr('action');
    alert(file);                             
    $.ajax({
        url: ajaxUrl, // point to server-side PHP script 
        type: 'POST',
        dataType: 'text',  // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: {
                name   : name,
                desc   : desc,
                price  : price,
                cat    : cat,
                amount : amount,
                image  : image,
                file

             },                         

        success: function(php_script_response){
            alert(php_script_response); // display response from the PHP script, if any
        }
     });

});

这是我的newItem.php

<?php


if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ){

    include "../database\connect.php";

    $item_name     = $_POST[ 'itemName' ];
    $item_desc     = $_POST[ 'itemDesc' ];
    $item_price    = $_POST[ 'itemPrice' ];
    $item_amount   = $_POST[ 'itemAmount' ];
    $item_category = $_POST[ 'category' ];


    $formErrors = array();

    if( empty( $item_name ) ){
        $formErrors[] = 'You should type the item name'; 
    }
    if( empty( $item_desc ) ){
        $formErrors[] = 'You should add item description';
    }
    if( empty( $item_price ) ){
        $formErrors[] = 'You should add item price';
    }
    if( empty( $item_amount ) ){
        $formErrors[] = 'You should type item amount';
    }
    if( $item_category == 0 ){
        $formErrors[] = 'You should select item category';
    }


    $item_picture = $_FILES[ 'itemPic' ];
    $picture_name = $item_picture[ 'name' ];
    $picture_temp = $item_picture[ 'tmp_name' ];
    $picture_size = $item_picture[ 'size' ];
    $picture_type = $item_picture[ 'type' ];

    if( empty( $picture_name ) ){
        $formErrors[] = 'You should select item picture';
    }



    /*

        Picture Extension
        -------------------

    */


        $extensions = array( "png", "jpg", "jpeg", "gif" );

        $picture_name_explosion = explode('.', $picture_name);
        $extension_name = end( $picture_name_explosion );
        $extension = strtolower( $extension_name );


        if( !in_array($extension, $extensions) && !empty( $picture_name ) ){
            $formErrors[] = 'This extension is not allowed';
        }
        if($picture_size > 4194304){
            $formErrors[] = 'Image Can\'t Be Larger Than 4MB';
        }

        if( empty( $formErrors ) ){

            $item_image = rand( 0, 1000000 ) . '_' . $picture_name;
            move_uploaded_file($picture_temp, '../layouts/images/items' . $item_image);

            $stmt = $db->prepare( "INSERT INTO Items( item_name, item_description, item_pic, item_price, amount,    added_date, cat_id ) VALUES( :zname, :zdesc, :zpic, :zprice, :zamount, :zdate, :zcat ) " );

            $stmt->execute( array(

                'zname'   => $item_name,
                'zdesc'   => $item_desc,
                'zpic'    => $item_image,
                'zprice'  => '$' . $item_price,
                'zamount' => $item_amount,
                'zdate'   => date( 'Y-m-d h:i:s' ),
                'zcat'    => $item_category

            ) );
            echo date( 'Y-m-d h:i:s' );
        }

        foreach ($formErrors as $error) {
            var_dump( $error );
        }
}

当我尝试上传时,我收到一条错误,即$ _POST数据未在newItem.php中定义

请帮助我,并提前感谢!

2 个答案:

答案 0 :(得分:1)

您不需要编写这么多代码 尝试将name属性提供给表单标签。

<form id="jqdata" enctype="multipart/form-data" method="post" class="add-new-item-form-form" name="jqdata" action="requests/newItem.php">

现在你的ajax电话:

var ajaxUrl = $(this).attr('action');
$(document).ready(function(){
    $('#submitNow').click(function(e){
        e.preventDefault();
        var form = $("#jqdata");
        var formdata = new FormData(form[0]);
         $.ajax({
                url: ajaxUrl,
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (output) {
                    alert(output);
                    $("#jqdata")[0].reset(); //reset all data from form.
                }
            });
    });
});

试试这个并告诉我它是否有效。

答案 1 :(得分:0)

如下所述更改变量分配:

$item_name     = $_POST[ 'name' ];
$item_desc     = $_POST[ 'desc' ];
$item_price    = $_POST[ 'price' ];
$item_amount   = $_POST[ 'amount' ];
$item_category = $_POST[ 'cat' ];

发布到newitems文件的数据是您在ajax请求中设置的数据。因此,您应使用的字段名称应更改为与ajax数据中设置的字段名称相匹配。