0

I need to create dynamically an HTML form in jQuery, and when i click the submit button, then i send the form datas via Ajax to the 'add_sw.php' which is process them.

But my problem is that this PHP script cant access the PHP $_FILES variable, so that is empty..

Here is the js relevant js codes:

<script type="text/javascript">
  $("body").on("click", "#submit", function() {
    var frm = $('#sw_add');
    frm.submit(function (ev) {
      $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
          alert('ok');
        }
      });

      ev.preventDefault();
    });
  });
</script>

<script type="text/javascript">
  $("body").on("change", "select", function() {
    var tag = $("<div></div>");
    var content = "<form id='sw_add' action='add_sw.php' method='post' enctype='multipart/form-data'>";
    content += "<input type='text' name='sw_name'>";
    content += "<label for='file'>Fájl:</label>";
    content += "<input type='file' name='file' size='40'>";
    content += "<textarea rows='4' cols='50' name='sw_comment'></textarea>";
    content += "<div class='buttons'><button id='submit' type='submit'>Save</button></div>";
    content += "</form>";
    tag.html(content).dialog({title:'Add new software', modal:false, width:500, height:360}).dialog('open');
  });
</script>

And the beginning the PHP script:

<?php
  $sw_name    = $_REQUEST['sw_name'];
  $sw_file    = $_FILES['file']['name'];
  $sw_comment = $_REQUEST['sw_comment'];

  // process the form datas...
?>

My problem is that the '$sw_file' variable is empty, i do not get the uploaded file name. Why?

szpal
  • 647
  • 9
  • 27

1 Answers1

1

I modified the first js script, and this is a working version.

<script type="text/javascript">
  $("body").on("click", "#submit", function() {
    $("#sw_add").submit(function(e) {
      var formObj = $(this);
      var formURL = formObj.attr("action");
      var formData = new FormData(this);
      $.ajax({
        url: formURL,
        type: 'POST',
        data:  formData,
        mimeType: "multipart/form-data",
        contentType: false,
        cache: false,
        processData: false,
        success: function(data, textStatus, jqXHR) {
          alert('ok');
        },
        error: function(jqXHR, textStatus, errorThrown) {
          alert('error');
        }          
      });
      e.preventDefault();
      e.unbind();
    }); 
  });
</script>
szpal
  • 647
  • 9
  • 27