0

I want to upload an image using input type="file" but when I seralize the form using JQuery serialize() method I can't able to get file name or other properties using $_FILES on PHP page.

<script type="text/javascript" src="AddNews.js"></script>

<form id="myForm" method="post" action="#" enctype="multipart/form-data" onsubmit="return false;">
   <div class="innerContainer">
      <table border="0" cellspacing="0" cellpadding="7" width="92%" align="center">
      <tbody>
      <tr>
          <td class="registerForm">Title:</td>
          <td><input type="text" id="title" name="title" size="35" /></td>
      </tr>    
      <tr>
          <td class="registerForm">Image Path:</td>
          <td><input type="file" id="file" name="file" /></td>
      </tr>
      <tr>
          <td class="registerForm">Content:</td>
          <td><textarea cols="35" rows="7" id="content" name="content"></textarea></td>
      </tr>
      </tbody>
      </table>
      <div id="submitButton">
          <input name="submit" type="submit" value="Add News" />
      </div>
   </div>
</form>

Below code is Javascript code for 'AddNews.js' file

$(document).ready(function() {
    $('input[name="submit"]').click(function() {
       if ($("#title").val().length == 0) {
           alert('Please Enter News Title ');
           return false;
       } 

       var formData = $("#myForm").serialize();
       $.post('AddFormLogic.php', formData, function(response) {

       }, 'json');
    });
});

/*PHP Code of AddFormLogic.php */
if ($_FILES["file"]["error"] > 0) {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
}

I am not able to access $_FILES["file"]["error"] on PHP page. Undefined index error.

Can some one help me?

4

1 回答 1

0

JQuery will not send input[type=file] serialising the form data. You can use the html5 class FormData. Try:

var formData = new FormData($("#myForm").[0]);

However, this will only work with browsers supporting html5.

于 2013-08-29T10:37:17.187 回答