douwei2825 2018-04-13 14:51
浏览 36
已采纳

文件上传未通过ajax提交

I created a form upload which contains some inputs but when I submitted the form to ajax, ajax was unable to grap the file name.

I keep on getting Notice: Undefined index: userImage in C:\wamp\www\osun\i_admin\php_action\uploadImage.php on line 14 . userImage is the name of the file

index.php

<?php include('header.php'); ?>
<?php include('top.php'); ?>
<?php include('links.php'); ?>

    <section class="content">
        <div class="container-fluid">
            <div class="block-header">
                <h2>Worker of the Month</h2>
            </div>

 <!-- Basic -->
 <div class="row clearfix">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="card">

                    <div id="error" class="closeit"></div>

                    <div id="messages"></div>

                         <div class="body">
                         <form  enctype="multipart/form-data" id="uploadImageForm">
                                 <div class="form-group form-float">
                                    <div class="form-line">
                                        <input type="text" class="form-control" name="name" id="name">
                                        <label class="form-label">Worker's Name</label>
                                    </div>
                                </div>

                                 <div class="form-group form-float">
                                    <div class="form-line">
                                        <input type="text" class="form-control" name="dept" id="dept">
                                        <label class="form-label">Department</label>
                                    </div>
                                </div>

                                <div class="form-group form-float">
                                            <div class="input-group">
                                               <div class="form-line">
                                                    <input type="text" data-type="date" id="date" name="date" placeholder="Date" class="form-control datepicker">

                                              </div>

                                             </div>
                                </div>

                                <div class="form-group form-float">
                                    <div class="form-line">
                                        <textarea name="description" id="description"  cols="30" rows="5" class="form-control no-resize"></textarea>
                                        <label class="form-label">Description</label>
                                    </div>
                                </div>


                            <div class="form-group">
                            <label for="exampleInputPassword1">Photo</label>            
                            <div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>

                            <div class="kv-avatar center-block" style="width:200px">
                                <input id="avatar-2" name="userImage" type="file" class="file-loading">
                            </div>
                        </div>


                                <div class="form-group" align="center">

                                <button type="input" name="submit"  class="btn btn-success btn-md btn-icon  waves-effect" id="btn-submit" ><i class="fa fa-check-square-o"></i> Save</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <!-- #END# Basic -->
      </div>
    </section>

<?php include('footer.php'); ?>  

uploadimage.php

include('../../includes/functions.php');

if($_POST) {

    $valid = array('success' => false, 'messages' => array());

    $name = $mysqli->real_escape_string($_POST['name']);// user name
    $dept = $mysqli->real_escape_string($_POST['dept']); 
    $desc = $mysqli->real_escape_string($_POST['description']);// user email
    $yr = $mysqli->real_escape_string($_POST['date']); 

    $fileName = $_FILES['userImage']['name'];

    $type = explode('.', $fileName);
    $type = $type[count($type) - 1];

    $url = '../user_images/' . uniqid(rand()) . '.' . $type;

    if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
        if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
            if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {

                // insert into database
                $sql = "INSERT INTO worker_of_the_month (name, dept, description, given, img) VALUES ('$name','$dept','$desc','$yr', '$url')";

                if($mysqli->query($sql) === TRUE) {
                    $valid['success'] = true;
                    $valid['messages'] = "Successfully Saved.";
                } 
                else {
                    $valid['success'] = false;
                    $valid['messages'] = "Error while saving. " . $mysqli->error;
                }

                $mysqli->close();

            }
            else {
                $valid['success'] = false;
                $valid['messages'] = "Error while saving. " . $mysqli->error;
            }
        }
    }

    echo json_encode($valid);

    // upload the file 
}

Ajax.js

$('document').ready(function() {
    /* validation */
    $("#uploadImageForm").validate({
        rules:
        {

         name:{
           required: true
         },

         dept:{
           required: true
         },


        description:{
          required: true
        },

        date:{
          required: true
        },

        },
        messages:
        {
          name: "Worker name required",
          dept: "Worker department name required",
          description: "Enter description for this honour.",
          date: "Please select date",
        },
        submitHandler: submitForm
    });
    /* validation */

    /* form submit */
    function submitForm()
    {
        var data = $("#uploadImageForm").serialize();

        $.ajax({

            type : 'POST',
            url  : 'php_action/uploadImage.php',
            data : data,
            beforeSend: function()
            {
                $("#error").fadeOut();
                $("#btn-submit").html('<img src="../img/processing.gif" width="30" /> &nbsp; processing');
            },
            success :  function(data)
            {
               if(data.success == true)
                {
                    $("#btn-submit").html('<img src="../img/processing.gif" width="30" /> &nbsp; Saving ...');
                    $("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                          data.messages + 
                        '</div>');

                          $('#uploadImageForm')[0].reset();
                     /*setTimeout(' window.location.href = "success.php"; ',4000);*/
                }
                else{

                    $("#error").fadeIn(1000, function(){

                        $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+data+' !</div>');

                        $("#btn-submit").html('<span class="fa fa-check-square-o"></span> &nbsp; Save');

                    });

                }
            }
        });
        return false;
    }
    /* form submit */

});
    </script>

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dougai2427 2018-04-13 15:02
    关注

    You need to use a FormData() to pass files.

    Change

    var data = $('#uploadImageForm').serialize();
    

    to

    var form = $('#uploadImageForm')[0];    
    var data = new FormData(form);
    

    As @ThisGuyHasTwoThumbs pointed you should set cache, contentType and processData via your ajax call

    $.ajax({
    cache: false,
    processData: false,
    contentType: false,
    //other ajax parameters
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘