图像不使用PHP和AJAX上传

时间:2017-12-05 16:09:36

标签: javascript php jquery ajax

我不知道自己做错了什么。我希望能够使用Ajax和PHP上传图像。

这是我的代码

HTML

<form id="edit-stock-image" >
        <div class="row">
                <div class="col-md-12">
                    <input type="hidden" name="id" id="stock-id">
                    <input type="file" class="form-control-file" id="image" name="image" aria-describedby="fileHelp">

                </div>
            </div>
        </div>
              <div class="modal-footer edit-stock-image-modal-footer"><br>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" id="save-edit-stock-image" class="btn btn-success ">Upload</button>
                </div>
 </form>

Jquery的

    $(document).on('click', '#save-edit-stock-image', function() {


           jQuery.ajax({
              url: '../data/stock-control.php?action=edit-stock-image',
              type: "POST",           
               data: new FormData(this), 
              processData: false, //prevent jQuery from converting your FormData into a string
              contentType: false,
              success: function(data, textStatus, jqXHR) {  
              console.log(2);
                 $('#edit-stock-image-modal').modal('hide');
                jQuery('#sc-sub-menu1').load('/tasks/stock-control/stock-control-process.php');


              },
                error: function(jqXHR, textStatus, errorThrown){

                //Display error message to user
                alert("An error occured when saving the data");
              }
        })

        });

PHP

if (!($update_stmt = $mysqli_scs->prepare("UPDATE `stock_stk` SET `image_stk`= ? WHERE (`id_stk`= ?) LIMIT 1;"))) {
    echo "Prepare failed: (" . $mysqli_scs->errno . ") " . $mysqli_scs->error;
    }

    if (isset($_POST['id'])) {
            $id = $_POST['id'];
        }

    if (isset($_FILES['image'])) {
        $image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
        }

        $update_stmt->bind_param("bi", $image,$id);
        //Execute the statement
        if (!$update_stmt->execute()) {
            echo "{success:false}";
        }
        // close statement 
        $update_stmt->close();
}

我正在使用blob保存图像。当用户浏览图像并选择一个并单击上传按钮时,我希望保存这些图像。

1 个答案:

答案 0 :(得分:0)

我认为你的ajax电话中有错误的网址:

$(document).on('click', '#save-edit-stock-image', function() {
    jQuery.ajax({
        // here you wrote '../' I think it's wrong.
        url: '../data/stock-control.php?action=edit-stock-image',
        // Another ajax params...
    });
});