In this tip i will help you to upload image using jQuery without using any other jQuery plugin. You can also check some other jQuery Tutorial’s.
CODE
First create new html file in your favorite text editor and copy below code. Before start writing code add jQuery plugin or jQuery CDN. Created simple html form for uploading image. I use jQuery Ajax Method to upload my image as shown below.
<html> <head> <title>Upload Image Using Ajax</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <form method="post" action="upload.php" id="upload"> <input type="file" name="img" value="" id="img"> <input type="submit" name="btn" value="Submit" /> </form> <div id="preview"></div> <script type="text/javascript"> jQuery("#upload").submit(function(e){ jQuery.ajax({ url: "upload.php", dataType: "json", type: "POST", data: new FormData(this), contentType: false, processData:false, cache: false, success: function(rsp){ console.log(rsp); if(rsp.status == "1"){ jQuery("#img").val(""); jQuery("#preview").html('<img src='+rsp.img+'>'); }else if(rsp.status == "0"){ alert(rsp.msg); } } }); e.preventDefault(); }); </script> </body> </html>
When image is uploaded to server it return output in json format.
<?php $name = $_FILES['img']['name']; $tname = $_FILES['img']['tmp_name']; if(copy($tname, $name)){ $res = array("status" => 1, "img" => $name); }else{ $res = array("status" => 0, "msg" => "error"); } header("content-type: application/json"); echo json_encode($res); ?>
🙂