In this blog post we accept covered one of the topic of ajax i.eastward. to upload images using Ajax and phpwithout page refresh.


Brusk Description :

In this process the image is selected first and previewed before storing it in to any location . Then using  jQuery Ajax, it is ship to php script on submit button effect.

PHP script stores the image in a divers location and returns the bulletin of the success and failure of the procedure.

Here we accept applied some validations on the selected file, to check information technology whether it is an prototype file (jpg, jpeg or png ) or any other file type.

Upload File size allowed is 100 Kb.


Following steps are pointed nether this process :

1.  Include jQuery library.

2.  HTML page with upload field.

3.  jQuery Ajax code.

3.  PHP script to shop image.

 Ajax Code :

                                  $.ajax({ url: "ajax_php_file.php", // Url to which the asking is send blazon: "Post",             // Blazon of request to be send, called every bit method information: new FormData(this), // Information sent to server, a gear up of cardinal/value pairs (i.e. course fields and values) contentType: fake,       // The content blazon used when sending data to the server. enshroud: false,             // To unable request pages to be buried processData:false,        // To send DOMDocument or not candy data file it is set up to false success: role(data)   // A office to be called if asking succeeds { $('#loading').hide(); $("#message").html(data); } });                              

PHP lawmaking used to shop the image :

                                  $sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable $targetPath = "upload/".$_FILES['file']['proper noun']; // Target path where file is to be stored move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file                              

Beneath is our complete code with the live demo and download option


HTML page containing file upload field.

HTML file : ajax_upload_image_main.php

                                  <html> <head> <championship>Ajax Image Upload Using PHP and jQuery</title> <link rel="stylesheet" href="style.css" /> <link href='http://fonts.googleapis.com/css?family unit=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' blazon='text/css'> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="script.js"></script> </head> <torso> <div class="main"> <h1>Ajax Paradigm Upload</h1><br/> <hour> <form id="uploadimage" action="" method="mail service" enctype="multipart/form-data"> <div id="image_preview"><img id="previewing" src="noimage.png" /></div> <hr id="line"> <div id="selectImage"> <label>Select Your Image</label><br/> <input blazon="file" name="file" id="file" required /> <input type="submit" value="Upload" class="submit" /> </div> </form> </div> <h4 id='loading' >loading..</h4> <div id="message"></div> </body> </html>                              

Complete jQuery Lawmaking : script.js

                                  $(document).set up(function (e) { $("#uploadimage").on('submit',(function(due east) { due east.preventDefault(); $("#message").empty(); $('#loading').show(); $.ajax({ url: "ajax_php_file.php", // Url to which the request is send type: "POST",             // Type of request to be ship, called equally method information: new FormData(this), // Data sent to server, a set of key/value pairs (i.east. course fields and values) contentType: fake,       // The content type used when sending data to the server. cache: simulated,             // To unable request pages to exist buried processData:false,        // To send DOMDocument or non processed information file it is set to false success: office(information)   // A function to exist called if request succeeds { $('#loading').hibernate(); $("#message").html(data); } }); }));  // Function to preview image after validation $(office() { $("#file").change(function() { $("#message").empty(); // To remove the previous mistake bulletin var file = this.files[0]; var imagefile = file.blazon; var match= ["image/jpeg","prototype/png","image/jpg"]; if(!((imagefile==match[0]) || (imagefile==friction match[1]) || (imagefile==match[2]))) { $('#previewing').attr('src','noimage.png'); $("#message").html("<p id='mistake'>Please Select A valid Epitome File</p>"+"<h4>Note</h4>"+"<bridge id='error_message'>Only jpeg, jpg and png Images type allowed</bridge>"); return fake; } else { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function imageIsLoaded(e) { $("#file").css("color","greenish"); $('#image_preview').css("display", "block"); $('#previewing').attr('src', due east.target.result); $('#previewing').attr('width', '250px'); $('#previewing').attr('height', '230px'); }; });                              

PHP Script : ajax_php_file.php

                                  <?php if(isset($_FILES["file"]["type"])) { $validextensions = array("jpeg", "jpg", "png"); $temporary = explode(".", $_FILES["file"]["name"]); $file_extension = stop($temporary); if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "epitome/jpg") || ($_FILES["file"]["type"] == "image/jpeg") ) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["fault"] . "<br/><br/>"; } else { if (file_exists("upload/" . $_FILES["file"]["name"])) { repeat $_FILES["file"]["proper name"] . " <span id='invalid'><b>already exists.</b></span> "; } else { $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable $targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file echo "<span id='success'>Paradigm Uploaded Successfully...!!</span><br/>"; echo "<br/><b>File Proper name:</b> " . $_FILES["file"]["name"] . "<br>"; echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>"; echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>"; } } } else { echo "<span id='invalid'>***Invalid file Size or Type***<span>"; } } ?>                              

CSS code : mode.css

                                  body { font-family unit: 'Roboto Condensed', sans-serif; } h1 { text-align: centre; background-color: #FEFFED; elevation: 70px; color: rgb(95, 89, 89); margin: 0 0 -29px 0; padding-top: 14px; border-radius: 10px 10px 0 0; font-size: 35px; } .master { position: accented; top: 50px; left: 20%; width: 450px; height:530px; border: 2px solid gray; border-radius: 10px; } .principal label{ colour: rgba(0, 0, 0, 0.71); margin-left: 60px; } #image_preview{ position: absolute; font-size: 30px; superlative: 100px; left: 100px; width: 250px; height: 230px; text-align: centre; line-height: 180px; font-weight: bold; colour: #C0C0C0; background-color: #FFFFFF; overflow: automobile; } #selectImage{ padding: 19px 21px 14px 15px; position: absolute; bottom: 0px; width: 414px; background-color: #FEFFED; border-radius: 10px; } .submit{ font-size: 16px; background: linear-slope(#ffbc00 5%, #ffdd7f 100%); border: 1px solid #e5a900; colour: #4E4D4B; font-weight: assuming; cursor: pointer; width: 300px; border-radius: 5px; padding: 10px 0; outline: none; margin-pinnacle: 20px; margin-left: fifteen%; } .submit:hover{ background: linear-gradient(#ffdd7f 5%, #ffbc00 100%); } #file { color: red; padding: 5px; border: 5px solid #8BF1B0; groundwork-color: #8BF1B0; margin-elevation: 10px; border-radius: 5px; box-shadow: 0 0 15px #626F7E; margin-left: 15%; width: 72%; } #message{ position:accented; summit:120px; left:815px; } #success { color:greenish; } #invalid { color:red; } #line { margin-top: 274px; } #error { color:cerise; } #error_message { colour:blueish; } #loading { display:none; position:absolute; top:50px; left:850px; font-size:25px; }                              

Determination :
In this blog postal service we have covered a basic topic of ajax of uploading paradigm using php with applied validations in it. Hope this might have worked for yous to understand the ajax property. Keep reading our other blog posts for more coding tricks.