doutou3725 2016-05-16 19:31
浏览 57
已采纳

使用Ajax PHP formData上传文件和数据提交XHR

hello friend i am trying to upload data and files at some time via ajax with this form:

<form id="formarea" class="form-horizontal" name="desk">
<input type="text" class="form-control " name="i_txt_2">
<input type="number" class="form-control " name="i_txt_3" required>
<input type="file" name='i_files_1'>
<input type="file" name='i_files_2'>
<input type="file" name='i_files_3'>
</form>

Ajax:

$('[id^="save"]').on("click", function (event, xhr, settings) {
        var id = event.target.id;
        var name = $("#formarea").attr("name");
        $.ajax({
            type:"POST",url:"index.php",data:$("#formarea").serialize()+ '&idprocess=' + id + '&idform=' + name,
                error: function(xhr,status,error){console.log(error)},
                success:    function(response) {
                    $("#areasmg").html(response);
                    $("#MsgArea").removeClass("").addClass("alert alert-warning alert-dismissable");
                    $("#MsgArea").show();
                }
            });
    });

issues: on request i am not received in server side php serialized of Input File: i_files_1 how can i concatenate the dile to data sent:

data:$("#formarea").serialize()+ '&idprocess=' + id + '&idform=' + name + '&Files' + files[]Serialized ,

UPDATE Problem Solved:

//If you have button to submit Form
$('[id^="BTN-"]').on("click", function (event, xhr, settings) {
    var id = event.target.id; //get id buton to filter if you like get control over the button clicked
    var req = 0;
    $('#formarea *').filter(':input').each(function(){ //filter all requiered input field
        if($(this).val() === "" && $(this).attr('required')){req ++;}
    });
    if(req == 0){
        var name = $("#formarea").attr("name"); //get name of form if you like get control over the form submited
        //window.WindowsWait();
        var input1 = $("<input>").attr("type", "hidden").attr("name", "idprocess").val(id); //Adding field for more controls if you neet handle from PHP
        var input2 = $("<input>").attr("type", "hidden").attr("name", "idform").val(name); //Adding field for more controls if you neet handle from PHP
        $('#formarea').append($(input1)); //inserting on Html
        $('#formarea').append($(input2)); //inserting on Html
        event.preventDefault(); //prevent default submit
        //get form an serialize data with FormData
        var $form       = $("#formarea"), 
            formData    = new FormData(),
            params      = $form.serializeArray();               
        var inputs = $("input[type=file]");
        //Get all Input tipe Files
        $.each(inputs, function (obj, v) {
            // Prefix the name of uploaded files with "uploadedFiles-"
            // Of course, you can change it to any string
            var file = v.files[0];
            var name = $(v).attr("name");//you can work with the name
            formData.append(name, file);
        });
        // Add all params to the formData
        $.each(params, function(i, val) {
            formData.append(val.name, val.value);
        });
        //performing the submit
        $.ajax({
            url: $form.attr('action'),
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            error: function(xhr,status,error){console.log(error)},
            success:    function(response) {
                alert(response);//print response server
            }
        });

    }else{
        alert("Error: You must fill all field, there " + req + " Empty Fields.");//handle Error Empty Fields
    }
});

Test:

print_r($_FILES);

  • 写回答

3条回答 默认 最新

  • douqu2712 2016-05-17 00:19
    关注

    UPDATE Problem Solved:

    //If you have button to submit Form
    $('[id^="BTN-"]').on("click", function (event, xhr, settings) {
        var id = event.target.id; //get id buton to filter if you like get control over the button clicked
        var req = 0;
        $('#formarea *').filter(':input').each(function(){ //filter all requiered input field
            if($(this).val() === "" && $(this).attr('required')){req ++;}
        });
        if(req == 0){
            var name = $("#formarea").attr("name"); //get name of form if you like get control over the form submited
            //window.WindowsWait();
            var input1 = $("<input>").attr("type", "hidden").attr("name", "idprocess").val(id); //Adding field for more controls if you neet handle from PHP
            var input2 = $("<input>").attr("type", "hidden").attr("name", "idform").val(name); //Adding field for more controls if you neet handle from PHP
            $('#formarea').append($(input1)); //inserting on Html
            $('#formarea').append($(input2)); //inserting on Html
            event.preventDefault(); //prevent default submit
            //get form an serialize data with FormData
            var $form       = $("#formarea"), 
                formData    = new FormData(),
                params      = $form.serializeArray();               
            var inputs = $("input[type=file]");
            //Get all Input tipe Files
            $.each(inputs, function (obj, v) {
                // Prefix the name of uploaded files with "uploadedFiles-"
                // Of course, you can change it to any string
                var file = v.files[0];
                var name = $(v).attr("name");//you can work with the name
                formData.append(name, file);
            });
            // Add all params to the formData
            $.each(params, function(i, val) {
                formData.append(val.name, val.value);
            });
            //performing the submit
            $.ajax({
                url: $form.attr('action'),
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                error: function(xhr,status,error){console.log(error)},
                success:    function(response) {
                    alert(response);//print response server
                }
            });
    
        }else{
            alert("Error: You must fill all field, there " + req + " Empty Fields.");//handle Error Empty Fields
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)