Simple file upload using ajax

AJAX, Javascript, jQuery 17 responses so far

Ajax ,an acronym for Asynchronous Javascript and Xml is a group of interrelated web development techniques used on the client side to create asynchronous web applications.With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page.

Storing  or retrieving data from database via ajax is more common and easier than uploading an image to server using ajax.Since ajax works without page refresh so uploading images too via ajax is a great technique to totally ajaxify your website and let the user have a smooth experience while scrolling various sections/pages of your website.

Below is the ajax script to upload file to server and perform get saved location file name as a response.

 <script type="text/javascript">
 function savepic()
 {
 //can perform client side field required checking for "fileToUpload" field
 $.ajaxFileUpload
 (
 {
 url:'doajaxfileupload.php',
 secureuri:false,
 fileElementId:'fileToUpload',
 dataType: 'json',
 success: function (data, status)
 {
 if(typeof(data.error) != 'undefined')
 {
 if(data.error != '')
 {
 alert(data.error);
 }else
 {
 alert(msg); // returns location of uploaded file
 }
 }
 },
 error: function (data, status, e)
 {
 alert(e);
 }
 }
 )
 return false;
 }
 </script>

Use this link to download additional files: [highlight] Files.rar[/highlight]

File upload is triggered by the click of a submit button as shown below:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<input type="file" name="fileToUpload" id="fileToUpload" />
<input type="button" value="Save" onclick="savepic()" /> //you can also use event listeners instead of onclick here
The following two tabs change content below.
I am a core php developer and web designer working as a freelancer in elance,odesk etc.

Latest posts by Mudit (see all)

  • http://cubicleninjas.com Cubicle Ninjas

    What a helpful article. I will definitely be integrating this with my current project. Thank you so much!

  • http://blogbuilding101.blogspot.com/ Tito

    Thank you. That’s perfect for what I needed.

  • http://www.olamsolutions.com web desiging company

    Great points on web designing.Its a really great. Thanks for sharing such great article.
    web desiging company

  • http://www.cloudcontracts.com raj

    it would be nice to have a demo of your code so we can see it in action.

  • http://www.dot-net-developer.net/hire-ajax-developers.html AJAX Developers

    Resources like the one you mentioned here will be very useful to me!

    AJAX developers can build powerful and reliable AJAX applications including websites and portals to boost your esteemed online business in today’s competitive online business environment.

    Ajax Developers

  • Leonard Prabangkoro

    all i get was “syntax error”… i’m really frustated

  • Shon MX

    File uploads are not possible using pure Ajax; however Uploadify does a work around using flash (uses jquery but is able to be used with other api’s since 2.0)

  • Ivo Ilic

    I keep getting this error:

    Uncaught TypeError: Object function ( selector, context ) {
    // The jQuery object is actually just the init constructor ‘enhanced’
    return new jQuery.fn.init( selector, context, rootjQuery );
    } has no method ‘handleError’

    Can anyone help?

  • John

    Garbage. Doesn’t work.

  • http://www.qtriangle.in/ Pushpraj Rathour

    I Will Paraphrasing And Post In My Website And Backlink To You

  • Spacer

    Done everything, carefully copy paste. Click to upload but nothing…. waste of time

  • codeLikeAMan

    Useless.

  • http://systemstrading.com Tradetree

    I think the point of this is to get you to hire the developer as there is too little documentation to be effective. I started debugging the javascript but it was too time consuming. I got the same “handleError” as others who posted. So it would be great to put together a few more steps involved, like what do you do with the js file that extends JQuery? I just loaded it, but most others people will not know how to do that as it is not documented. – Still doesn’t work for me overall.

  • Jacob

    Hi there,

    When I upload the file I get this error message: ReferenceError: msg is not defined

    Any ideas?

  • Camilo

    Hi!!!
    Thanks for the tutorial, but you need to add a few details.
    First add on the beginning of the script handle.error ajaxfileupload.js because jquery does not have this function.

    jQuery.extend({

    handleError: function( s, xhr, status, e ) {
    // If a local callback was specified, fire it
    if ( s.error )
    s.error( xhr, status, e );
    // If we have some XML response text (e.g. from an AJAX call) then log it in the console
    else if(xhr.responseText)
    console.log(xhr.responseText);
    },

    Second replace alert (msg), for alert (error.msg);

    $.ajaxFileUpload
    (
    {
    url:'doajaxfileupload.php',
    secureuri:false,
    fileElementId:'uploadfile',
    dataType: 'json',
    success: function (data, status)
    {
    alert(data);
    if(typeof(data.error) != 'undefined')
    {
    if(data.error != '')
    {
    alert(data.error);
    }else
    {
    alert(data.msg); // returns location of uploaded file
    }
    }
    },
    error: function (data, status, e)
    {
    alert(e);
    }
    }
    )

    Works perfectly with jasny fileupload http://jasny.github.io/bootstrap/javascript.html # fileupload :)

  • Taha A

    Replace line 20 – 22
    {
    alert(msg); // returns location of uploaded file
    }

    with

    {
    alert(data.msg); // returns location of uploaded file
    }

  • binkumar1999

    test data

x
Loading...