Sunday, May 20, 2012

Upload file to server using ajax and php

Include jquery.form.js and jquery.min.js

<script type="text/javascript" src="/js/jquery.form.js"></script>
<script type="text/javascript" src="/js/jquery.min.js"></script>

jQuery("#contact-form").ajaxForm({
    beforeSubmit: function() {
        jQuery.showBackgroundWorkingState();
    },
    success: function(data) {
        /*console.log(data);*/
        try {
            if(data == CONSTANT_JS_SUCCESS_CODE) {

            } else {
                jQuery.showWarning("Error uploading file, please try again later.");       
            }
        } catch ( ex ) {
            jQuery.showWarning("Error uploading file, please try again later.");
        }
        jQuery.hideBackgroundWorkingState();
    },
    error: function() {
        jQuery.showWarning("Error uploading file, please try again later.");
        jQuery.hideBackgroundWorkingState();
    }
}).submit(); 
 
File save using php script:

<?php
$name = $_FILES['photoimg']['name'];
list($txt, $ext) = explode(".", $name);
$tmp = $_FILES['photoimg']['tmp_name'];
$docRoot = $_SERVER["DOCUMENT_ROOT"];
$imageLocation = $docRoot . "/app/webroot/img/";
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
if(move_uploaded_file($tmp, $imageLocation.$actual_image_name)) {
    die("1");
}
die("0"); 
?>

No comments:

Post a Comment