9

During trying to combine submit and upload in one form, I have a problem in upload but for submit form it's no problem.

JQuery + Ajax :

$("#oqcsubmit").click(function() {
    if($("#oqc").valid()) {
            var params=$("#oqc").serialize();
                $.ajax({
                    type:"post",
                        url:"doinput.php",
                        data:params,
                        cache :false,
                        async :false,
                        success : function() {
                            $(".dt").val("");
                                $(".stat").val("");
                                return this;
                                },
                        error : function() {
                            alert("Data failed to input.");
                                }
                        });
                 return false;
                 }
     });

<form id="oqc" enctype="multipart/form-data" >
    <input type="text" id="mod" name="mod" class="dt"/>
    <input type="text" id="no" name="no" class="dt"/>
    <input id="filename" name="uploadedfile" type="file" />
    <input type="submit" id="oqcsubmit" value="Submit" />
    <input type="hidden" name="action" value="oqcdata" />
</form>

PHP :

$dbc=mysql_connect(_SRV,_ACCID,_PWD) or die(_ERROR15.": ".mysql_error());
$db=mysql_select_db("QPL",$dbc) or die(_ERROR17.": ".mysql_error());

$target_path = "data/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
//print_r($_FILES);
        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
                echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
                }
        else{
                echo "There was an error uploading the file, please try again!";
                }

switch(postVar('action')) {
        case 'oqcdata' :
                oqcdata(postVar('mod'),postVar('no'));
                break;
        }

function oqcdata($mod,$no) {

        $Model          = mysql_real_escape_string($mod);
        $Serial         = mysql_real_escape_string($no);

//build query
  $sql = "INSERT INTO OQC (Model, Serial) VALUES ('".$Model."','".$Serial."')";
echo $sql;
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
echo $result;
mysql_close($dbc);

how to put the upload code correctly in this page? so both could working. directory permission :chmod 777 data


the file is left behind in the form after submit (not send) . file lagging


UPDATE

After move the upload code before switch I got thi error:

PHP Notice:  Undefined index: uploadedfile

it's mean that the form not send the uploadedfile value. After check the parameter there are no uploadedfile included. why it happens? even this value is included inside the form and using .serialize().

form data :
mod:KD-R321ED
no:177X1000          // where is the uploaded file value?
action:oqcdata
Charles
  • 50,943
  • 13
  • 104
  • 142
nunu
  • 2,703
  • 9
  • 33
  • 55
  • What error is coming?? Because code is correct may be the server has not given proper permission for saving a file. – Yogesh Suthar Dec 14 '12 at 04:45
  • 1
    Refer this thread in [stackoverflow][1] [1]: http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery – DeDav Dec 14 '12 at 04:48
  • not show error message, but if I check to `data/` the file isn't uploaded. – nunu Dec 14 '12 at 04:48
  • @YogeshSuthar: the permission is 777 for this directory. – nunu Dec 14 '12 at 04:58

6 Answers6

2
PHP Notice:  Undefined index: uploadedfile

it's mean that the form not send the uploadedfile value. After check the parameter there are no uploadedfile included. why it happens?

You can not upload files over vanilla cross-browser ajax, such as that which jQuery uses. Period, full stop, end of story.

If you must do the upload without a page refresh, the common trick is to create an iframe and submit the form to it. Another trick is to use the experimental File API, exposed as part of HTML5. These can be a pain to handle yourself, but it should work well if you want to do it all by hand.

I highly recommend using a third-party file upload widget for this. I've had luck with Plupload, but some people also recommend Uploadify. They can both optionally use a Flash or HTML5 backend to perform the upload, which also gives users a happy little progress meter.

Charles
  • 50,943
  • 13
  • 104
  • 142
  • did you mean better I using separate process (separate submit & upload) instead of this combine form? – nunu Dec 20 '12 at 07:34
  • 1
    You can combine non-file things and files together, but you can *not* upload files through standard cross-browser ajax. The reason I recommend third party code here, by the way, is so that *that* code manages the complexity involved. – Charles Dec 20 '12 at 08:26
0

You should use XHR2 to upload files through AJAX .

An example :

Javascript / Clientside:

function upload() {
    var fileInput = document.getElementById('file_input_upload'); 
    var file = fileInput.files[0];        

    xhr = new XMLHttpRequest();

    xhr.open('post', 'upload.php', true);
    xhr.setRequestHeader("Content-Type", "application/octet-stream");
    xhr.setRequestHeader("Cache-Control", "no-cache");  
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");  
    xhr.setRequestHeader("X-File-Name", file.name);  
    xhr.setRequestHeader("X-File-Size", file.size);  
    xhr.setRequestHeader("X-File-Type", file.type);   
    xhr.send(file);
}

HTML :

<input type="file" id="file_input_upload"/>
<div onmousedown="upload()">Upload my file</div> 

PHP / Serverside (upload.php):

$file_name = $_SERVER['HTTP_X_FILE_NAME'];
$file_size = $_SERVER['HTTP_X_FILE_SIZE'];
file_put_contents(
            "data/" . $file_name, 
            file_get_contents("php://input")
        );

This was a simple example without any error checking . So please do not use this code for production use . And if you want to upload large files(in GB) you should use webworkers

adi rohan
  • 796
  • 1
  • 10
  • 26
  • could you explain with jquery ? – nunu Dec 20 '12 at 07:30
  • Big fat warning: this code **bypasses** PHP's standard file upload handling mechanism, including the safety measures of a server-set maximum upload size, a safe and sane temporary file, and forgoes even the most basic operations, like including the file's *name* and original MIME type. It also relies on the *working draft* [FileAPI](http://www.w3.org/TR/FileAPI/), which is *not* yet implemented in all or even *most* browsers. – Charles Dec 20 '12 at 08:30
  • @charles , **i said that my code is not meant for production use** . Can you please suggest a method of doing it using the " PHP's standard file upload handling mechanism "? Also , xhr2 is implemented in most browsers except IE [link](http://caniuse.com/xhr2). – adi rohan Dec 20 '12 at 09:00
0

You can use Uploadify to handle the file upload. It offers "onUploadSuccess" callback function. From where you can get the uploaded file info (filename,path etc). You can use that info and update a hidden input field in your form. And then you can access the information on the server side and manipulate it.

Hope this helps.

Faraz
  • 156
  • 3
  • 13
0

It is impossible to send file input data via $.ajax only. I have successfully used jQuery form plugin http://malsup.com/jquery/form/. It wraps any form into AJAX processing, and adds a lot of useful callback options. It also does some clever things to handle file uploads. For older browsers (which do not support XHR Level 2) there might be some very minor additional server-side modifications, but otherwise it works out of the box.

For specific docs on using jQuery form to handle file uploads see http://malsup.com/jquery/form/#file-upload

Igor Raush
  • 15,080
  • 1
  • 34
  • 55
0

Better is using a simply way, with separate process :

$("#oqcsubmit").click(function() {
    if($("#oqc").valid()) {
            var params=$("#oqc").serialize();
                $.ajax({
                    type:"post",
                        url:"doinput.php",
                        data:params,
                        cache :false,
                        async :false,
                        success : function() {
                            $(".dt").val("");
                                $(".stat").val("");
                                return this;
                                },
                        error : function() {
                            alert("Data failed to input.");
                                }
                        });
                 return false;
                 }
     });

<form id="oqc">
    <input type="text" id="mod" name="mod" class="dt"/>
    <input type="text" id="no" name="no" class="dt"/>
    <input type="submit" id="oqcsubmit" value="Submit" />
    <input type="hidden" name="action" value="oqcdata" />
</form>

<form enctype="multipart/form-data" action="uploader.php" method="POST"> 
    Upload File: <input id="filename" name="uploadedfile" type="file" />
    <input id="upload" type="submit" value="Upload File" style="display:none;"/>
</form>

both can works normally,the best way is do not do the complicated way if the easy one can be done.

nunu
  • 2,703
  • 9
  • 33
  • 55
-2

for uploading files through ajax go through this url ajax file uploading

Habid Pk
  • 218
  • 2
  • 7
  • -1, links are not answers. When that link dies, your question is useless. Please provide a summary of the content on the linked page. – Charles Dec 20 '12 at 05:41