简体   繁体   English

如何在表单提交中包含ID?

[英]How to include the id in the submission of the form?



Goal: 目标:
1. To include the id (in this example the id = 1) when the upload form is submitted so that it can be accessed in submit.php 1.在提交上载表单时包括ID(在本示例中为ID = 1),以便可以在Submit.php中对其进行访问

2. To insert the filename into the sql db depending on the id. 2.根据ID将文件名插入sql db。

Form: 形成:

<form action="#" enctype="multipart/form-data" method="post">
<input type="hidden" name="name" id="1">
<input type="file" name="upload" id="upload" >
<input class="button" type="submit" name="submit" value="Submit Content">
</form>

Script: 脚本:

$('input[type=file]').on('change', prepareUpload);
$('form').on('submit', uploadFiles);

function prepareUpload(event)
{
    files = event.target.files;
}

function uploadFiles(event)
  {
    event.stopPropagation(); 
    event.preventDefault(); 

    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
        url: 'submit.php?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, 
        contentType: false, 
        success: function(data, textStatus, jqXHR)
        {
            console.log('Successfully uploaded the file');
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('Failed to upload the file');
        }
    });
}


submit.php submit.php

<?php 
  $data = array();

  if(isset($_GET['files']))
  { 
    $error = false;
    $files = array();

    $uploaddir = 'uploads/';

    foreach($_FILES as $file)
     {
       if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
       {
        $files[] = $uploaddir .$file['name'];
        }
     else
       {
        $error = true;
       }
     }
   $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
 }
 else
 {
  $data = array('success' => 'Form was submitted', 'formData' => $_POST);
 }

 echo json_encode($data);
 ?>


Thanks so much! 非常感谢!

将您的隐藏字段更改为此:

<input type="hidden" name="id" value="1">

You can use your hidden field as 您可以将隐藏字段用作

<input type="hidden" name="my_id" id="my_id" value="1">

And now within your jquery simply use 现在,在您的jquery中,只需使用

var my_id = $('#my_id').val();

And pass it with data 并传递data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM