How get data and files in PHP from FormData

孤人 提交于 2019-12-24 10:40:34

问题


I'm trying send data (input text, dropdown list, etc) and files to PHP file through Ajax. I use this function to add extra parameter named Action. Action can be some of these texts: "add", "edit", "read" and "delete" (crud options). See the script below:

function recordActions(action_name, id) {
  //id = (typeof id == "undefined") ? '' : id;

  var frm = document.getElementById(action_name + '_form');
  var form_data = new FormData();

  form_data.append('action', action_name);
  form_data.append('fd', frm);

  $.ajax({
          type: 'post',
          dataType: 'json',
          url: '<?php echo FILENAME_USERS_ACTIONS; ?>',
          data: form_data, 
          cache: false,
          processData: false,
          contentType: false,
          success:
            if (data.action == 'add' || data.action == 'edit') {
                $("#" + action_name + '_form')[0].reset();
                $("#" + action_name + '_div').slideUp();
            }
            showWeekAgenda();

            }          
      });

      // esta línea evita que la página se refresque dando a Cancelar la visita y evita que salga Error en Success de Arriba
      if (action_name == 'cancel') return false; 
    }

When the Ajax call the PHP file (), I don't know how to access the data contains in FormData. Seeing the Params in Web Developer, I got it:

-----------------------------81668061412059330971865480216
Content-Disposition: form-data; name="action"

actadd
-----------------------------81668061412059330971865480216
Content-Disposition: form-data; name="fd"

[object HTMLFormElement]
-----------------------------81668061412059330971865480216--

Then, I put some code in PHP to see the params and their values:

print_r($_POST);
print_r($_FILES);

echo '<br>Post: ' . $_POST['fd'];

but I got nothing to help me.

Array
(
    [action] => actadd
    [fd] => [object HTMLFormElement]
)
Array
(
)
<br>Post: [object HTMLFormElement]

Anyone knows how to access to any value inside of fd? fd should have values of my input texts, dropdown, textarea, etc.

Following the answer of this question: Uploading both data and files in one form using Ajax? we can put all HTML Controls in one FormData.

Thanks in Advance!


回答1:


When you create your FormData object, you should pass the form to the constructor to get it populated with the forms values. You can then append the action value to that result:

var frm = document.getElementById(action_name + '_form');
var form_data = new FormData(frm);
form_data.append('action', action_name);

When you do it this way you should see $_POST and $_FILES populated correctly in your PHP code.



来源:https://stackoverflow.com/questions/54166663/how-get-data-and-files-in-php-from-formdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!