user1863337
user1863337

Reputation: 13

Jquery submit function cannot post uploaded document to a php script

Have been trying to post uploaded document alongside other text fields to a php script using jquery's submit function but so far unsuccessful. The text fields are successfully posted. I have no idea what the problem is. PLease assist.

Jquery submit code

    submitHandler: function(form) {

            $.post('bin/insert.php', $("#form").serialize(), 
            function(data) {
              if(data.length > 0 )
              {
                  $('.success_box').fadeIn(800);
                 $('.success_box').html(data);
              }

            });
            }

php script

            if(isset($_POST['save']))
   {
            $upload_dir = "./docs"; 
    $upload_path = $upload_dir."/";
    $userfile_name = $_FILES['image']['name'];
    $userfile_tmp = $_FILES['image']['tmp_name'];
    $userfile_size = $_FILES['image']['size'];
    $filename = basename($_FILES['image']['name']);
    $file_ext = substr($filename, strrpos($filename, '.') + 1);
    $large_image_name  = $filename;
            if($userfile_name==NULL){
    echo "<img src='./warning.png' align='center'>You have not selected a      document to upload";
    exit();
}
}

I get the above error message on posting the form.

Upvotes: 0

Views: 82

Answers (2)

Anish
Anish

Reputation: 5038

Yes you can upload file suing ajax script. Use the below code

$(document).ready(function(){
        $('form#id').submit(function(event){            
            var formData = new FormData($(this)[0]);
            $.ajax({
                type : "POST",
                url : "bin/insert.php",
                data : formData,
                async :false,
                dataType : 'json',
                success: function(data,status)  {           
                               alert('saved');
                        },
                cache: false,
                contentType: false,
                processData: false
            });             
            event.preventDefault();
        });
    });

On php page try print_r($_POST); print_r($_FILES);

Process these and put into db and move the file to you file locations.

Upvotes: 0

steve
steve

Reputation: 2519

AJAX can't be used for uploading files to a server.

There are a few plug-ins that may help including:

http://www.webtoolkit.info/ajax-file-upload.html

Noticed as posting this link and others on the SO link provided above in comments - that page has a good source of info for you.

Upvotes: 1

Related Questions