views:

661

answers:

2

Hi all,

i have a problem with jquery form plugin. I try to upload a file asynchronously but it does not submit the form. html markup and javascript code are like below

<form id="fileUploadForm" method="post" action="Default.aspx" enctype="multipart/form-data">
<input type="text" name="filename" />
<input type="file" id="postedFile" name="postedFile" />
<input type="button" value="Submit" onclick="UploadFile();" />
</form>

$(document).ready(function() {

        $('#fileUploadForm').ajaxForm();            
    });

function UploadFile() {

        var options =
        {                
            url:"Default.aspx",                
            beforeSend: ShowRequest,
            success: SubmitSuccesfull,
            error:AjaxError                               
        };            
        $("#fileUploadForm").ajaxSubmit(options);
        return false;
    }. 

I have another test form it has only a textbox in it and it works fine. Also when i comment the input type="file"... line the above form works fine too. What is the problem with input type file? Any Idea?

+1  A: 

In short:

<input type="file" />

Cannot be submitted via ajax, it has to be a full postback. Traditionally you use an iFrame for this if you want AJAX style behavior. I've used a few solutions to this, without knowing what platform you're on, SWFUpload is usually a good option.

Here's a full document example of a fix:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title></title>
    <script type="text/javascript" src="Javascript/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="Javascript/jquery.form.js"></script>
    <script type="text/javascript">
        $(function() {            
          $('#fileUploadForm').ajaxForm({                 
            beforeSubmit: ShowRequest,
            success: SubmitSuccesful,
            error: AjaxError                               
          });                                    
        });            

        function ShowRequest(formData, jqForm, options) {
          var queryString = $.param(formData);
          alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
          return true;
        }

        function AjaxError() {
          alert("An AJAX error occured.");
        }

        function SubmitSuccesful(responseText, statusText) {        
          alert("SuccesMethod:\n\n" + responseText);
        }    
    </script>
</head>
<body>
    <form id="fileUploadForm" method="POST" action="Default.aspx" enctype="multipart/form-data">
      <input type="text" name="filename" />
      <input type="file" id="postedFile" name="postedFile" />
      <input type="submit" value="Submit" />
    </form>
</body>
</html>
Nick Craver
Thanks for your responsecould you check the link below http://jquery.malsup.com/form/#file-uploadam i misunderstanding it?
mehmet6parmak
@mehmet6parmak - Added alternative above, give it a shot, see if you still have issues. Are you using FireBug or something to see if any action/error is taking place?
Nick Craver
i did not use firebug but i debug it in visual studio however i could not understand what is happening inside jquery(indeed as you mentioned above it creates an iframe thats the only thing i understood =)).I tried to use jquery's error handler but that method never executed. If i find the problem i'll write it here thanks again for your interest.
mehmet6parmak
@mehmet6parmak - If you could expose it to a URL I could see, I'd be happy to take a look as well, just comment if that's possible.
Nick Craver
Here http://clients.entegral.com.tr/test/jqueryfileupload.htm there are two forms -one in each line-. Second form works fine.
mehmet6parmak
@mehmet6parmak - Got some time to look at it, your main problem is `beforeSend` interferes with the forms behavior in this case, changed it to `beforeSubmit` (updated answer above!) Also, if you change the button type to be `type="submit"` like above, it'll invoke the ajaxForm behavior automatically. I also condensed the code down a bit to show a shorter way, but same `beforeSend` problem either way. Hope this gets you going!
Nick Craver
Hello Nick,May you tell me why I cannot add dataType: 'json'to the option list?It always report errors.thank you
q0987
A: 

I worked my own sample and your own code, but I don't get the $_FILES data, means the array data for file upload in Server page. I am using PHP, and have this code:

index.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title></title>
    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <script type="text/javascript" src="jquery.form.js"></script>
    <script type="text/javascript">
        $(function() {            
          $('#fileUploadForm').ajaxForm({                 
            beforeSubmit: ShowRequest,
            success: SubmitSuccesful,
            error: AjaxError                               
          });                                    
        });            

        function ShowRequest(formData, jqForm, options) {
          var queryString = $.param(formData);
          alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
          return true;
        }

        function AjaxError() {
          alert("An AJAX error occured.");
        }

        function SubmitSuccesful(responseText, statusText) {        
          alert("SuccesMethod:\n\n" + responseText);
        }    
    </script>
</head>
<body>
    <form id="fileUploadForm" method="POST" action="default.php" enctype="multipart/form-data">
      <input type="text" name="filename" />
      <input type="file" id="postedFile" name="postedFile" />
      <input type="submit" value="Submit" />
    </form>
</body>
</html>

default.php:

<?php
if ($_FILES['postedFile']['error'] > 0) {
        $upl = '<br />Error: ' . $_FILES['postedFile']['error'] . '<br />';
    } else {
        $upl = '<br />Upload: ' . $_FILES['postedFile']['name'] . '<br />';
        $upl .= 'Type: ' . $_FILES['postedFile']['type'] . '<br />';
        $upl .= 'Size: ' . ($_FILES['postedFile']['size'] / 1024) . ' Kb<br />';
        $upl .= 'Stored in: ' . $_FILES['postedFile']['tmp_name'];
                move_uploaded_file($_FILES["postedFile"]["tmp_name"],"images/".$_FILES["postedFile"]["name"]); //move file to server
    }
    echo $upl; // output the result
} else {
    die('Invalid entry!');
}
?>

What am I doing wrong?

Anes
You should post follow-up questions as a separate thread, notas an answer. After all, it doesn't really answer *this*question. Also more people would see it and try to answer if you post it asyour own question.
sth