Bluemagica
Bluemagica

Reputation: 5158

Jquery ajax file upload problem

How do you upload a file in jquery through ajax? form.serialize() won't get the file content, and I don't want to use plugins.

Upvotes: 1

Views: 2105

Answers (2)

kcho0
kcho0

Reputation: 169

The best thing you can do is make the file upload using another form (below your main form) witch sends the uploaded file path to the main form -when it success-.

Look the code in here and I make this changes to work like yours:

In the head

<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>

<script type="text/javascript">
$(document).ready(function () {
$('#photoimg').live('change', function() {                      
                        $("#preview").html('');
                        $("#preview").html('<br/>Colocando archivo...<br /><img src="img/loader.gif" alt="Uploading...."/>');               
        $('#imageform').bind('submit', function(e) {
            e.preventDefault(); // <-- important
            $(this).ajaxSubmit({
                target: '#preview',
                success: function() {
                $('#file').val($('#newimg').attr("src"));
                }               
            });
        }).submit();        

        });
    });
});
</script>

Image form:

<form id="imageform" method="post" enctype="multipart/form-data" action='class/db_manager.php'>
<label for="alias">*Imagen</label>
<input type="file" name="photoimg" id="photoimg" /><input type="hidden" name="MM_insert_img" value="imageform" />
</form><p>Image</p><div id='preview'></div>

Main form:

<form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="f_insert_cliente" id="f_insert_cliente">
<label for="file">Imagen</label>
//when file uploads, this is where we will place the relative path
<input name="file" type="text" id="file" value="" />
</form>

PHP file

if ((isset($_POST["MM_insert_img"])) && ($_POST["MM_insert_img"] == "imageform")) {

    $path = "../img/uploads/";

    $valid_formats = array("jpg", "png", "gif", "bmp");
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
        {
            $name = $_FILES['photoimg']['name'];
            $size = $_FILES['photoimg']['size'];

            if(strlen($name))
                {
                    list($txt, $ext) = explode(".", $name);
                    if(in_array($ext,$valid_formats))
                    {
                    if($size<(1024*1024))
                        {
                            $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                            $tmp = $_FILES['photoimg']['tmp_name'];
                            if(move_uploaded_file($tmp, $path.$actual_image_name))
                                {                               

                                    echo "<br />Vista previa:<br /><img src='img/uploads/".$actual_image_name."'  class='preview' id='newimg'>";
                                }
                            else
                                echo "failed";
                        }
                        else
                        echo "Image file size max 1 MB";                    
                        }
                        else
                        echo "Invalid file format..";   
                }

            else
                echo "Please select image..!";

            exit;
        }
}

?>

So how does it works:

  1. user uploads the file and the event is handdled by the jquery function (remember to add in the head the scripts/js)
  2. php return the uploaded image tag code (or error)
  3. jQuery handdle the event and look for the image SRC attribute and set it as value of the another form text input

Hope it helps, be free to ask :)

Upvotes: 1

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

I don't think you can do it from form.serialize()

Upvotes: 0

Related Questions