Rafee
Rafee

Reputation: 4078

File upload in php Ajax jQuery not working

I have simple two pages as index.php and ajx_upload.php. And a directory for uploading files as upload

Below are the code

Index.php

<table>
    <form name="profileimage" id="profileimage" method="post"  enctype="multipart/form-data" >
        <tr>
            <td><img id="partner_pic" src="" height="100" width="100" /></td>
        </tr>
        <tr>
            <td><input type="file" name="fileimg1" id="fileimg1" /></td>
        </tr>
        <tr>
            <td><p id="pic_profile_p"></p></td>
        </tr>
        <tr>
            <td><input type="submit" name="uploadimg" value="Change Picture" /></td>
        </tr>
    </form>

</table>

ajx_upload.php

<?php 
     $target = "upload/"; 
     $target = $target . $_FILES['fileimg1']['name'] ; 
     $ok=1; 
     if(move_uploaded_file($_FILES['fileimg1']['tmp_name'], $target)) 
     {
         echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
     } 
     else {
         echo "Sorry, there was a problem uploading your file. <br />" . $_FILES['fileimg1']['error'];

     }
?> 

No image or not only single is uploaded, instead it gives an error

Notice: Undefined index: fileimg1 in D:\xampp\htdocs\mywesbite\mydriectory\ajx_upload.php on line 3

Notice: Undefined index: fileimg1 in D:\xampp\htdocs\mywesbite\mydriectory\ajx_upload.php on line 5

jQuery Code

 $("#profileimage").submit(function(){

        var data = $(this).serialize();
        $.post('ajx_upload.php', data, function(return_data){
            $('#pic_profile_p').html(return_data)
        });


        return false;
    });

I dont know why file is not uploaded.

Upvotes: 0

Views: 4256

Answers (1)

Ray Perea
Ray Perea

Reputation: 5851

If you want to upload files but use ajax, like camus said, you can't... But you can create the illusion of an ajax file upload... a little trick I use is submitting the form to a hidden iframe and then using ajax once the upload is finished to continue in your workflow as if the file was uploaded via ajax. The upload happens and the page never gets refreshed.

Check out this article http://www.openjs.com/articles/ajax/ajax_file_upload/

Upvotes: 1

Related Questions