aidron
aidron

Reputation: 127

jQuery and php file upload

I do not understand, and google does not give me the answer. I want to upload a file and the results show in the div without page relode, but I can not get it!!!!

html:

<form method="post" action="process/pic2.php" enctype="multipart/form-data" id="userpic">
<p>Izvēlies bildi: <input type="file" name="img_to_upload" /><input type="submit" name="upload" value="Augšupielādēt" /></p>
</form>

jquery:

jQuery(function(){
        jQuery('#userpic').submit(function(){
            jQuery.ajax({
                type: 'POST',
                enctype: 'multipart/form-data',
                url: jQuery('#userpic').attr('action'),
                data: jQuery('#userpic').serialize(),
                success: function(data){
                    if(data){
                        jQuery('#picinfo').html(data);
                    }else{
                        jQuery('#uerpic').fadeOut(500);
                        jQuery('#picinfo').html('<center><img src="img/loader.gif" /></center>');
                            window.location = 'index.php';
                    }
                }
            });
            return false;
        });
    });

and my php:

if(isset($_FILES['img_to_upload']['name']) && !empty($_FILES['img_to_upload']['name'])){
        echo 'Done!';
    }else{
        echo 'Error!';
    }

all the time showing the "error" text..

P.S. Sorry for bad English.

Upvotes: 2

Views: 655

Answers (1)

jbnunn
jbnunn

Reputation: 6355

Normally, to do a form-submission, and stay on the same page, you'll have to prevent the default form action with Javascript, something like this:

$("#userpic").submit(function(event) {
  event.preventDefault();
  ...
});

But, uploading an image via Ajax is pretty tricky--see:

uploading files with jquery $.ajax and php

Upvotes: 1

Related Questions