【问题标题】:Form field input isn't received by JSON AJAX scriptJSON AJAX 脚本未接收到表单字段输入
【发布时间】:2021-06-27 06:22:55
【问题描述】:

我无法从表单中获取 $productid。不知道我做错了什么。有什么想法吗?

选择的文件会上传,但不会上传到指定的产品文件夹,并且没有任何关于成功的信息返回到index.php

这很奇怪,但是在尝试发布“看起来您的帖子主要是代码;请添加更多详细信息”时,stackoverflow 也提到了,但我没有更多信息要添加?

谢谢

index.php

    <form method='post' action='' enctype="multipart/form-data">
    <input type="hidden" id='productid' name="productid" value="<?=$productid?>">
    <input type="file" id='files' name="files[]" multiple><br>
    <input type="button" id='submitphotos' value='Upload'>

    <!-- Preview -->
    <div id='successupload'></div>
    <div id='preview'></div>
<script>

  $(document).ready(function(){

    $('#submitphotos').click(function(){

      var form_data = new FormData();

      // Read selected files
            var totalfiles = document.getElementById('files').files.length;
            var productid= $("#productid").val();
            for (var index = 0; index < totalfiles; index++) {
                form_data.append("files[]", document.getElementById('files').files[index]);
            }

            // AJAX request
            $.ajax({
                url: 'ajaxfile.php',
                type: 'post',
                data: form_data,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {

              for(var index = 0; index < response.length; index++) {
                  var src = response[index];

              // Add img element in <div id='preview'>
              $('#preview').append('<img src="'+src+'" width="400px;">');
              }

              $('#successupload').append('<h6>Successfully uploaded</h6><a href="back.php">back</a>');
              files.style.display = "none";
              submitphotos.style.display = "none";


                }
            });
    });
  });
ajaxfile.php

// Count total files
$countfiles = count($_FILES['files']['name']);

// Get product id
$productid = $_POST['productid'];

//Create request id folder if doesn't exist
if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/')) {
        mkdir($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/', 0777, true);
}

// Upload directory
$upload_location = $_SERVER['DOCUMENT_ROOT']."/images/products/".$productid."/";

// To store uploaded files path
$files_arr = array();

// Loop all files
for($index = 0;$index < $countfiles;$index++){

    if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){

        // File name
        $filename = $_FILES['files']['name'][$index];

        // Get extension
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        // Valid image extension
        $valid_ext = array("png","jpeg","jpg","svg");

        // Check extension
        if(in_array($ext, $valid_ext)){

            // File path
            $path = $upload_location.$filename;

            // Upload file
            if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
                $files_arr[] = $path;
            }
        }
    }

}

echo json_encode($files_arr);
die;

</script>

【问题讨论】:

  • 看起来您在发送表单数据之前没有将产品 ID 附加到表单数据中。
  • 谢谢@TangentiallyPerpendicular,不知道我会怎么做?我正在学习中
  • form_data.append(... 也许?您正在为下面两行的文件数组执行此操作。
  • 好的,谢谢,我一直在尝试使用教程来理解这一点。我补充说:form_data.append("productid", document.getElementById('productid'); 但一定还是做错了..
  • form_data.append("productid", document.getElementById('productid').value);这行得通,但我没有得到 #preview 和 #successupload 之后显示...

标签: php json ajax forms file-upload


【解决方案1】:

您还没有将 productid 传递给 ajax 调用,所以在 ajax 调用之前添加:

form_data.append('productid', productid);

您的代码应该可以正常工作。

【讨论】:

  • 谢谢,但这是唯一对我有用的。 form_data.append("productid", document.getElementById('productid').value);
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 2016-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
相关资源
最近更新 更多