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 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 Spring MVC项目,访问不到相应的控制器方法
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal
  • ¥15 STM32CubeIDE下载程序报错
  • ¥15 微信好友如何转变为会员系统?(相关搜索:小程序)
  • ¥15 c# 直接使用c++ 类库文件
  • ¥15 一个主机电脑有两个显示器,当前有两个软件主体是网页html打包的exe程序,如何通过cmd命令bat同时打开软件一个在主屏幕显示,另外一个软件在2副屏幕上显示