2

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.

1 Answer 1

1

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

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

1 Comment

Nope. Works with simply returning false. preventDefault is required on links etc, but not forms.

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.