0

I've a question about file uploading with Ajax. How to submit file with $.ajax() without a special js-plugin?:

<form action="javascript:return false;">
    <input type="text" id="name" />
    <input type="file" id="myfile" />
    <input type="button" id="submitbutton" value="submit" />
</form>

This is a jQuery small code:

<script type="text/javascript">
    $(document).ready(function() {
        $('#submitbutton').click(function() {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                enctype: 'multipart/form-data',
                url: 'upload.php',
                async: false,
                data: {
                    'name': $('#name').val(),
                    'myfile': $('#myfile').val()
                },
                success: function(data) {
                    alert(data.msg);
                }
            });
        });
    });
</script>

And upload.php file:

<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
if (isset($_FILES) && isset($_FILES["file"])) {
    $files = $_FILES['file'];
    $error = isset($files["error"]) ? $files["error"] : '';
    $fname = isset($files["name"]) ? $files["name"] : '';
    $type = isset($files["type"]) ? $files["type"] : '';
    $size = isset($files["size"]) ? $files["size"] : '';
    $tmp_name = isset($files["tmp_name"]) ? $files["tmp_name"] : '';
    return array('msg' => "Hello, $name! \nYour file data:\nErr: $error, Name: $fname, Type: $type, Size: $size, Tmp: $tmp_name");
}
echo json_encode(array('msg' => 'create image'));
?>
CSᵠ
  • 10,049
  • 9
  • 41
  • 64
user2228586
  • 191
  • 1
  • 2
  • 7

3 Answers3

1

Other option is using iframe, this is a tutorial for doing this;

egig
  • 4,370
  • 5
  • 29
  • 50
1

Files cannot be uploaded via ajax. You may want to checkout the Form Plugin which does support file uploads: http://jquery.malsup.com/form/

Dineshkumar
  • 351
  • 1
  • 8
0

If you expect to get this working cross browser, than you can't do that with AJAX only. (But it is ok for you that this will work not in all browsers, you may take a look how to upload files with XMLHttpRequest and jquery here)

As for me, the best would be to use jQuery Forms plugin.

Another option is to do the same thing that plugin does manually.

It will be something like below:

var ifrm = $("<iframe>", {id:"tmp_upload_frame"}).onload(function() {
  // do something when response is returned
}).hide();
$("body").append(ifrm);
$("form").prop("target", "tmp_upload_frame")
         .prop("enctype","multipart/form-data")
         .submit();

But as for me, Forms plugin is much better as it has an interface very similar to ajax interface and does a lot of dirty work for you (like retrieving response from iframe) for you.

Community
  • 1
  • 1
Viktor S.
  • 12,736
  • 1
  • 27
  • 52