Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file-upload using jquery post

Let me know if anyone know what is the issue with this code.

Basically i want to upload a file using jQuery

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>

  <script type="text/javascript">
    $(document).ready(function(event) {
      $('#form1').submit(function(event) {
        event.preventDefault();
        $.post('post.php',function(data){
           $('#result').html(data);
        });
      });
    });
  </script>  
</head>
<body>
<form id="form1">
  <h3>Please input the XML:</h3>
  <input id="file" type="file" name="file" /><br/>
  <input id="submit" type="submit" value="Upload File"/>
</form>

<div id="result">call back result will appear here</div>

</body>
</html>

and my php 'post.php'

<?php
  echo $file['tmp_name'];
?>

Uploaded File name is not returned back. Issue is i couldn't access the uploaded file.

Thanks in advance! Shiv

like image 813
Shiv Avatar asked Jun 15 '12 07:06

Shiv


1 Answers

Basically i want to upload a file using jQuery

You cannot upload files using AJAX. You could use the jquery.form plugin which uses a hidden iframe:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script type="text/javascript">
        $(document).ready(function(event) {
            $('#form1').ajaxForm(function(data) {
                $('#result').html(data);
            });
        });
  </script>  
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
    <h3>Please input the XML:</h3>
    <input id="file" type="file" name="file" /><br/>
    <input id="submit" type="submit" value="Upload File"/>
</form>

<div id="result">call back result will appear here</div>

</body>
</html>

Also notice the enctype="multipart/form-data" on the form.

Another possibility is to use the HTML5 File API which allows you to achieve that assuming the client browser supports it.

like image 165
Darin Dimitrov Avatar answered Nov 06 '22 22:11

Darin Dimitrov