2

I am trying to upload a file via AJAX and PHP. I have a HTML form as below:

<form method="post" id="sectiononeform" name="sectiononeform" enctype="multipart/form-data">

    <div class="clearfix">
        <input type="text" name="customHeading1" id="customHeading1" class="span10" value=""/>
    </div>

    <!-- Gets replaced with TinyMCE, remember HTML in a textarea should be encoded -->
    <div class="clearfix">
        <textarea id="elm1" name="elm1" rows="15" class="xxlarge" cols="80" style="width: 80%">

        </textarea>
    </div>

    <div class="clearfix">
        <input type="file" name="file1" id="file1" class="span10" />
    </div>

    <div class="clearfix">        
        <div class="actions">
            <input type="submit" id="saveSection1" name="saveSection1" value="Submit" />
            <input type="reset" name="resetSection1" value="Reset" />                
        </div>
    </div>

</form>

My jquery code is as follows:

$(document).ready(function(){
    $("#saveSection1").click(function(e){
        e.preventDefault();

        var formdata = false;

        /*function showUploadedItem (source) {
            var list = document.getElementById("image-list"),
                li   = document.createElement("li"),
                img  = document.createElement("img");
            img.src = source;
            li.appendChild(img);
            list.appendChild(li);
        }   */

        if (window.FormData) {
            formdata = new FormData();

            //document.getElementById("btn").style.display = "none";
        }

        var len = document.getElementById("file1").files.length, img, reader, file;

        for (var i = 0 ; i < len; i++ ) {
            file = document.getElementById("file1").files[i];
            if (!!file.type.match(/image.*/)) {
                if (window.FileReader ) {
                    reader = new FileReader();
                    /*reader.onloadend = function (e) { 
                        showUploadedItem(e.target.result, file.fileName);
                    };*/
                    reader.readAsDataURL(file);
                }
                if (formdata) {
                    alert("form data");
                    formdata.append("customHeading1", document.getElementById("customHeading1").value);
                    formdata.append("elm1", document.getElementById("elm1").value);
                    formdata.append("custsection1", 1);
                    formdata.append("venue_id", document.getElementById("venue_id").value);
                    formdata.append("images[]", file);
                    alert(formdata);
                }
            }   
        } 
        var params = $("form#sectiononeform").serialize();
        //alert("params" + params);
        params = params + "&custsection1=1&venue_id=" + $("#venue_id").val() + "&formdata=" + formdata;
        //alert(params);
        $.ajax({
          type: 'POST',
          url: 'saveCustomSectionData.php',
          data: formdata,
          success: function(data){
            alert(data);
          }
        });
    });
});

My issue is that when I don't use the file input type, I can just serialize the form values and send it through AJAX. Since I am using file input type, I am using formdata and appending information to it. Is this the right way to send data. I am not getting any response back from php, neither can i see any request in firebug. Instead I get some vague error as "Illegal operation on WrappedNative prototype object". Any suggestions?

2 Answers 2

13

You can use AJAX to send files. Using new FormData() and the $.ajax method with contentType: false, processData: false.

Check this out:

<script type="text/javascript">
$(document).ready(function()
{
    $("#ajax").hide();

    $("#botonancho").click(function()
    {
        if ($("#ficherocsv").val() =="")
        {
            alert("   Seleccione 1º el archivo ");  
        }
        else
        {
            var data = new FormData();
            data.append( 'file', $( '#ficherocsv' )[0].files[0] );

            $("#botonancho").val("Por favor... espere.");
            $("#ajax").html("<img src='imagenes/ajax-indicator.gif' alt='Indicador Actividade Ajax' />").show();

            $.ajax({
                url: 'importacion.php',
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data)
                {
                    $("#ajax").html("");

                    $("#ajax").html(data).fadeIn("slow",function()
                    {
                        $("#ajax").delay(1500).fadeOut("slow",function()
                        {
                            $("#botonancho").val("IMPORTAR Alumnos CSV (codificación UTF-8)");
                            $("#ficherocsv").val("");
                            $("#ajax").hide();

                        });
                    });
                }
            }); 
        }
    });

});
</script>

Regards.

Sign up to request clarification or add additional context in comments.

2 Comments

not sure I am going to try this as I finished this project, but will vote up for your efforts. Probably someone else might benefit.
Yeah..! Using FormData, we can send files also in ajax request..!
0

so far as i know this is not possible due to security reasons.

but it is possible to use something like jquery.form.js (available from http://jquery.malsup.com/form/) and is quite easy to implement.

they do also provide some nice examples for you to try aswel.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.