Ajax上载图像以及表单中的其他数据

时间:2018-09-13 10:24:27

标签: php jquery ajax

我的问题是:我想使用ajax上传image/pdf。在我的代码中,我有多个输入,但是我没有使用FormData()将数据从input传递到我的upload.php。一切工作完美。因此,这里有更好的想象:

$('#addData').on('click', function(){

        var c_zakazky = $('#c_zakazky').val();
        var pozicia = $('#pozicia').val();
        var p_cislo = $('#p_cislo').val();
        var stav = $('#stav').val();
        var tech = $('#tech').val();
        var zar = $('#zar').val();
        var operator = $('#op').val();

        var d = new Date();
        var month = d.getMonth()+1;
        var day = d.getDate();
        var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;

        //alert(dokument);

        $.ajax({
            url: 'add.php',
            type: 'POST',
            processData: false,
            contentType: false,
            data: {
                otk: 1,
                c_zakazky: c_zakazky,
                pozicia: pozicia,
                p_cislo: p_cislo,
                stav: stav,
                tech: tech,
                zar: zar,
                operator: operator,
                datum: datum
            },
            success: function(data){
                $('#live_data').html(data);
                $('#modalInsert').modal('hide');

                $('#c_zakazky').val();
                $('#pozicia').val();
                $('#p_cislo').val();
                $('#stav').val();
                $('#tech').val();
                $('#zar').val();
                $('#op').val();
                $('#dokument').val();

                fetch_data_otk();
                alert(data);
            }
        });
    });

现在如果我想将图像隐藏起来,该怎么做?我尝试添加以下内容:

var data = new FormData();
        data.append('image', $('#image').prop('files')[0]);
        console.log(data);

但是当我选择图像/ pdf并在控制台(数据)中点击“上传”时,它是空的,我不知道该怎么做。

5 个答案:

答案 0 :(得分:1)

如果要使用console formdata对象属性,请尝试此操作。

// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

// Display the key/value pairs
for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}

答案 1 :(得分:0)

我无法理解,您到底想要什么,但是请尝试以下代码,它将提交所有表单元素数据:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&post1&post2",
    success : function(){
    },
    error : function(){
   }
}

OR

$.ajax({
  url: 'url',
  type: "POST",
  data:  new FormData(this),
  success : function(){
  },
  error : function(){
  }
});

答案 2 :(得分:0)

请查看示例代码,将您的数据和图像/媒体文件保存到form_data,然后使用AJAX将所述数据保存在后端

<!DOCTYPE html>
        <head>
            <title>Example</title>
        </head>

        <body>
            <form enctype="multipart/form-data" id="add-hotel-form">
                <div class="form-group col-md-12">
                    <label for="hotel">Upload Hotel Images</label>
                    <input type="file" class="form-control-file" id="upload_img" name="img_url" multiple>
                </div>

                <input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
            </form>
        </body>

        <script>
        function myfunction(){

            var form_data = new FormData();

            var image = document.getElementById('upload_img').files.length;


            for (var x = 0; x < image; x++) {
                form_data.append("image", document.getElementById('upload_img1').files[x]);
            }

            $.ajax({
                url : 'your-backend-file-with-DB-Query.php',
                method : 'POST',// OR GET
                data: form_data,
                dataType: 'json',
                success:function(data) {

                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
                    alert("responseText: "+xhr.responseText);
                }

            }); 
        }
        </script>
    </html>

答案 3 :(得分:0)

这就是我的工作方式 附加表单数据,

var formData = new FormData(your_form);
 // for multiple files , because i need to check

new_files是类,我使用是因为我正在动态创建表单 还添加动态数据

$.each($(".new_files"), function (i, obj) {
//                console.log(obj.files);
        $.each(obj.files, function (j, file) {
              var max_size = 5120000;
              var file_type= file.type;
              var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
            // after validation etc
       //   append formdata
           formData.append('file[' + j + ']', file);
            });
  });
  // if you want something else, 
  formData.append("id", $('#kreditornr').val());
  // ajax

  $.ajax({
     type: "POST",
     url: "url",
     data: formData,
     contentType: false, // The content type used when sending data to the server.
     cache: false, // To unable request pages to be cached
     processData: false, // To send DOMDocument or non processed data file it is set to false
       success: function (data) {
          // success
       }
    });

答案 4 :(得分:0)

因此,谢谢您的帮助。现在,它可以完美运行。解决方案:

我只更改了脚本(php代码仍然相同)

//pridanie udajov
    $('#addData').on('click', function(){

        var fileInput = document.querySelector('form input[type=file]');
        var attachment = fileInput.files[0];

        var d = new Date();
        var month = d.getMonth()+1;
        var day = d.getDate();
        var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;

        var formData = new FormData();

        formData.append('otk', 1);
        formData.append('c_zakazky', $('#c_zakazky').val());
        formData.append('pozicia', $('#pozicia').val());
        formData.append('p_cislo', $('#p_cislo').val());
        formData.append('stav', $('#stav').val());
        formData.append('tech', $('#tech').val());
        formData.append('zar', $('#zar').val());
        formData.append('op', $('#op').val());
        formData.append('datum', datum);
        formData.append('image', $('#image').prop('files')[0]);

        console.log(formData);

        $.ajax({
            url: 'add.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data){
                $('#live_data').html(data);
                $('#modalInsert').modal('hide');

                $('#c_zakazky').val();
                $('#pozicia').val();
                $('#p_cislo').val();
                $('#stav').val();
                $('#tech').val();
                $('#zar').val();
                $('#op').val();
                $('#dokument').val();

                fetch_data_otk();
                alert(data);
            }
        });
    });