Skip to main content

Image upload in folder using ajax

Image upload in folder using ajax :


Basic information about ajax:
All people know about what is ajax and how it work,below information is explained.


AJAX is a new technique for creating better,faster,and more interactive web applications with the help of XML,HTML,CSS,and Java Script
Before you start ajax you will be much and more knowledge about java script,its important for us.ajax is not difficult it can be easily implementation.
Following advantage of ajax call:


1-Speed,
2-Interaction,
3-XMLHttpRequest,
4-Asynchronous call,
5-Form Validation,
6-Bandwidth Usage,


AJAX Disadvantages
1-Open Source:View source is allowed and anyone can view the code source written for AJAX,
2-It can increase design and development time,
3-Security is less in AJAX application as all files are downloaded at client side.


Events
This is the full list of Ajax events,and in the order in which they are triggered.The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.
ajaxStart (Global Event)
This event is triggered if an Ajax request is started and no other Ajax requests are currently running.
beforeSend (Local Event)
This event,which is triggered before an Ajax request is started,allows you to modify the XMLHttpRequest object (setting additional headers,if need be.)
ajaxSend (Global Event)
This global event is also triggered before the request is run.
success (Local Event)
This event is only called if the request was successful (no errors from the server,no errors with the data).
ajaxSuccess (Global Event)
This event is also only called if the request was successful.
error (Local Event)
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
ajaxError (Global Event)
This global event behaves the same as the local error event.
complete (Local Event)
This event is called regardless of if the request was successful,or not.You will always receive a complete callback,even for synchronous requests.
ajaxComplete (Global Event)
This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
ajaxStop (Global Event)
This global event is triggered if there are no more Ajax requests being processed.


FormData


1-HTML5 introduces FormData to allow developers to build forms objects dynamically.
2-send form object via Ajax,
3-contentType always false because otherwise boundary string will be missing,


Syntax :
 contentType :false


processData is set as false because otherwise formData convert data into string,
Syntax :
 processData :false


jQuery will make FormData cross browser. Whilst most browsers have supported FormData since the stone age (Chrome 7, Firefox 4.0 and Safari 5),


Syntax :  


var formData = new FormData(id-of-form);


above syntax define FormData() function and create object using new keyword,


Demo link :




Code link :


Following basic jquery and ajax function use :


Beforesend :


Purpose: I need to create animation while loading data by ajax and prevent another query for the html tag (users can click on the link over and over again).


Implementation: append events "beforeSend", "complete" in ajax-plugin and realize single instance of ajax request by html elements in ajax-plugin.


Error :
When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.


Success :
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function,


Following file create or folder structure :
1-header.php,
2-footer.php,
3-index.php,
4-action.php,
5-create folder “upload”.


1-index.php :



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Image upload in folder using ajax</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  <script   src="https://code.jquery.com/jquery-3.1.1.js"   integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="   crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<!-- start:header -->
<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">    
      <a class="navbar-brand" href="#">Free Teachnology</a>
    </div>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home <span class="sr-only"></span></a></li>
        <li><a href="#">About us</a></li>  
        <li><a href="#">Contact us</a></li>        
      </ul>
      </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
</br></br></br>
<!-- end:header →




2-footer.php :


<script>
// $(".errorMsg").alert('close');
$(".errorMsg").slideUp(2000);
</script>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Start::footer  -->
<footer>
        <div class="footer footer-bottom">

        <div class="container">  
           <div class="text-muted ">
               <a href="https://freeteachnology.blogspot.in/" >Free Teachnology</a>
            </div>
            <p class="pull-left"> Copyright © <?php echo date('Y');?>. Design and Develop by - Disuza Jen. </p>
            <div class="pull-right">
                <ul class="nav nav-pills payments">
                    <li><i class="fa fa-facebook"></i></li>
                    <li><i class="fa fa-google"></i></li>
                    <li><i class="fa fa-twitter"></i></li>
                    <li><i class="fa fa-link"></i></li>
                </ul> 
            </div>
        </div>
    </div>
    <!--/.footer-bottom--> 
</footer>
<!-- End::footer  -->
<style type="text/css">
  .footer-bottom {
    margin-top:220px;
    background: #E3E3E3;
    border-top: 1px solid #DDDDDD;
    padding-top: 10px;
    padding-bottom: 10px;
}
.footer-bottom p.pull-left {
    padding-top: 6px;
}
</style>
</body>
</html>


3-index.php :



<?php include('header.php'); ?>

<?php

session_start();

if (!empty($_SESSION['statusMsg'])) {
   echo '<p>' . $_SESSION['statusMsg'] . '</p>';
   unset($_SESSION['statusMsg']);
}
?>
<body>   
<br><br><br>
<div class="cleafix"></div>
<div class="container">
<div class="alert alert-info">
   <strong>Hi..</strong> >Image upload in folder using ajax.
</div>
      <div class="alert alert-warning">
       <a href="https://drive.google.com/open?id=0BxmTZPVcu72fbGN5TXc1YUVRUVE" class="btn btn-xs btn-warning pull-right" target="blank();">Click</a>
       <strong> Code download link-</strong>
   </div>
      
<div class="container-fluid well span3 ">
 <form method="post" name="uploadProfile" id="uploadProfile" enctype="multipart/form-data">
<div class="row">        
       <div class="col-lg-3 parentClass">
        <h6>Browse image</h6>
           <input type="file" accept="image/*" name="profile_img" id="profile_img" >
        </div>
            <div class="clearfix"></div>
            <br>
            <button type="button" name="uploadProfile" id="uploadProfile" value="submit" class="btn subbtn">Submit</button> </div>
     </form>
</div>
       </div>
</br>
<?php include('footer.php'); ?>
<script>

$('#uploadProfile').click(function () {
   
   var formData = new FormData($('#uploadProfile')[0]);
   if (formData != '') {
       $.ajax({
           type: 'post',
           data: formData,
           url:'action.php',
           async: false,
           cache: false,
           contentType: false,
           processData: false,
           beforeSend: function () {
               $('#uploadProfile').attr('disabled', 'true');
               $("#uploadProfile").html('Uploading...');
           },
           success: function (data) {
               $('#uploadProfile').removeAttr('disabled');
               $("#uploadProfile").html('Submit');
               //console.log(data);
               var data = $.parseJSON(data);
               // alert(data.result);                  
                   window.location.href = "index.php";
               },
           error: function (error) {                
               $('#uploadProfile').attr('disabled', 'false');
               $("#uploadProfile").html('Submit');
           }
       });
   } else {    
       $('#uploadProfile').attr('disabled', 'false');
       $("#uploadProfile").html('Submit');
   }
 
});

</script>






Above index.php file call ajax function following function call is important in upload files,


  type: 'post',
           data: formData,
           url:'action.php',
           async: false,
           cache: false,
           contentType: false,
           processData: false,


Now simple ajax call cache false etc.


Following only jquery ajax code :



<script>

$('#uploadProfile').click(function () {    

   var formData = new FormData($('#uploadProfile')[0]);
   if (formData != '') {
       $.ajax({
           type: 'post',
           data: formData,
           url:'action.php',
           async: false,
           cache: false,
           contentType: false,
           processData: false,
           beforeSend: function () {
               $('#uploadProfile').attr('disabled', 'true');
               $("#uploadProfile").html('Uploading...');
           },
           success: function (data) {
               $('#uploadProfile').removeAttr('disabled');
               $("#uploadProfile").html('Submit');
               //console.log(data);
               var data = $.parseJSON(data);
               // alert(data.result);                  
                   window.location.href = "index.php";
               },
           error: function (error) {                
               $('#uploadProfile').attr('disabled', 'false');
               $("#uploadProfile").html('Submit');
           }
       });
   } else {    
       $('#uploadProfile').attr('disabled', 'false');
       $("#uploadProfile").html('Submit');
   }
 
});
</script>



4-action.php
action .php file include file move code and response send jsonecnode,


Following code is :


<?php

session_start();

if(isset($_FILES['profile_img'])){
     $errors= array();
     $file_name = $_FILES['profile_img']['name'];
     $file_size =$_FILES['profile_img']['size'];
     $file_tmp =$_FILES['profile_img']['tmp_name'];
     $file_type=$_FILES['profile_img']['type'];
     $file_ext=strtolower(end(explode('.',$_FILES['profile_img']['name'])));
           $expensions= array("jpeg","jpg","png");
           if(in_array($file_ext,$expensions)=== false){
        // $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      $_SESSION['statusMsg'] = '<div class="alert alert-danger errorMsg" role="alert">
                                         <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                           <span aria-hidden="true">&times;</span>
                                         </button>
                                        <strong>Sorry!</strong> extension not allowed, please choose a JPEG or PNG file. </div>';    
         $response = array('result' => 'error');
       echo json_encode($response);
       exit;
     }      
     if($file_size > 2097152){
      $_SESSION['statusMsg'] = '<div class="alert alert-danger errorMsg" role="alert">
                                         <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                           <span aria-hidden="true">&times;</span>
                                         </button>
                                        <strong>Sorry!</strong> File size must be excately 2 MB.
                                       </div>';    
         $response = array('result' => 'error');
       echo json_encode($response);
       exit;      
     }
           if(empty($errors)==true){
        move_uploaded_file($file_tmp,"upload/".$file_name);
        $_SESSION['statusMsg'] = '<div class="alert alert-success errorMsg" role="alert">
                                         <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                           <span aria-hidden="true">&times;</span>
                                         </button>
                                        <strong>Thanks!</strong> Profile image uploaded successfully.
                                       </div>';
   
         $response = array('result' => 'SUCCESS');
       echo json_encode($response);
       exit;
  
     }else{
        print_r($errors);
     }
  }

?>



Above action.php file check file type ,file size file name etc,
Move the file in particular folder which is make


Function :


move_uploaded_file($file_tmp,"upload/".$file_name);


5-make folder “upload” whenever file is move then upload on “upload” folder


Now above example is good and i hope that you can understand,


If you like my blog please comment and like,share post

Thanks

Comments

Popular posts from this blog

using PDO database connection add,update,delete,edit operation

PDO advantage : 1-Object Oriented 2-Bind parameters in statements (security) 3-Allows for prepared statements and rollback functionality (consistency) 4-Throws catcheable exceptions for better error handling (quality) 5-Exception mode; no need to check error state after each API call. It's best to tell PDO how you'd like the data to be fetched. You have the following options: 1-PDO::FETCH_ASSOC: returns an array indexed by column name. 2-PDO::FETCH_BOTH: (default):returns an array indexed by both column name and number. 3-PDO::FETCH_BOUND:Assigns the values of your columns to the variables set with the ->bindColumn() method. 4-PDO::FETCH_CLASS: Assigns the values of your columns to properties of the named class. It will create the properties if matching properties do not exist. 5-PDO::FETCH_INTO:Updates an existing instance of the named class. 6-PDO::FETCH_LAZY: Combines. 7-PDO::FETCH_BOTH/PDO:FETCH_OBJ, creating the object variable names as t...

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links

Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links user want to share any information then use following code  and read step by step Profile Share Fixing the Thumbnail Image, Title and Description for Shared Links if you want share profile on following social link : 1-Facebook 2-twitter.com 3-LinkedIn 4-google +, Code link : https://drive.google.com/open?id=1IzTZZh_0euDqFSHL_vPRiQePlNTw3h-q Demo link : http://freeteachnology.hol.es/socialshare/ To modify a page's thumbnail image, description, and additional metadata for these services, you can provide meta tags in the HTML code of the page.Implementing Open Graph Meta Tags You can implement meta tags in a number of ways. In content management systems might  be allow you to modify a page's meta tags , then use following code in meta section of your project code, <link href="bootstrap.min.css" rel="stylesheet"> <link href="bootstrap-tour.m...

GUID for globally unique identifier

How to create GUID in php 1-guid stands for globally unique identifier generally used to create random unique strings in php, create access token in php 2-Mostly use of GUID for generating access token, generate unique id, generating unique string in php. Using this article how to create guide in php you can create a random string for any use to keep unique 3-GUID consists of alphanumeric characters only and is grouped in five groups separated by hyphens as seen in this example: 3F2504E0-4F89-11D3-9A0C-0305E82C3301 Eg:- <?php /** * Generate Globally Unique Identifier (GUID) * E.g. 2EF40F5A-ADE8-5AE3-2491-85CA5CBD6EA7 * * @param boolean $include_braces Set to true if the final guid needs * to be wrapped in curly braces * @return string */ function generateGuid($include_braces = false) { if (function_exists('com_create_guid')) { if ($include_braces === true) { return com_create_guid(); } else { return substr(com_cr...