I am trying to write a code to upload images to my server. I have found one and it works.
This is the code
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="file" id="file" />
<button onclick="uploadFile();">Upload</button>
<script type="text/javascript">
function uploadFile() {
var input = document.getElementById("file");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
</script>
</body>
</html>
PHP:
<?php
$dir = "upload/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
?>
Now I have to put multiple form file inputs, so I tried doing the following:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="file" id="one" />
<button onclick="uploadFile1();">Upload</button>
<input type="file" id="two" />
<button onclick="uploadFile2();">Upload</button>
<script type="text/javascript">
function uploadFile1() {
var input = document.getElementById("#one");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
function uploadFile2() {
var input = document.getElementById("#two");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
</script>
</body>
</html>
But it doesn't work, I found that file type and id of the file form should be the same in order to make it work. What am I doing wrong here? How can I solve this problem?
You don't include the # when using getElementById (you're giving it an id value, not a CSS selector), so:
var input = document.getElementById("#one");
// Remove this ----------------------^
...and similarly for #two.
But you don't have to repeat the entire function just to use a different file input. Change your function to accept an id argument:
function uploadFile(id) {
var input = document.getElementById(id);
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('File Uploaded');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
Then:
<button onclick="uploadFile('one');">Upload</button>
and
<button onclick="uploadFile('two');">Upload</button>
Related
using ajax to upload image url in database but i got error when submit form. I want upload image url im database without page refresh. Error is GET https://api.ciuvo.com/api/analyze?url=http%3A%2F%2Flocalhost%2F&version=2.1.3&tag=threesixty&uuid=C473346A-075C-48CD-A961-F4B68EFE2C4F 400 (Bad Request)
**html code**
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>
**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#message").html(data);
}
});
}));
});
php code
<?php
$host="localhost";
$user="root";
$pass="";
$db="test";
$con=mysqli_connect($host,$user,$pass);
mysqli_select_db($con,$db);
if (isset($_FILES["file"]["type"])) {
$dir = "images/";
$imagelocation=$dir.basename($_FILES['txtimg']['name']);
$extension = pathinfo($imagelocation,PATHINFO_EXTENSION);
if($extension != 'jpg' && $extension != 'png' && $extension != 'jpeg')
{
echo"plzz upload only jpg,jpeg And png";
}
else
{
if(move_uploaded_file($_FILES['txtimg']['tmp_name'],$imagelocation) )
{
if(mysqli_query($con,"Insert into img (img_url) values($imagelocation')"))
{
echo"SUCCESSFULLY";
}
}
else {
echo"ERROR";
}
}
}
?>
You should not call FormData object inside ajax request,
html code
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>
**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
var fdata = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: fdata,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#message").html(data);
}
});
}));
});
Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>
I have html form:
<form enctype="multipart/form-data" id="formUpload">
<input type="file" name="file" />
<button type="submit" id="sub">Click</button>
</form>
My script:
$(function() {
$("#sub").on("click",function () {
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
I try to upload file in upload.php, but all is wrong.
How can I get $_FILES variable?
Every time you click on submit button, your page will get refreshed and you won't see any output from this statement $("#res").html(data);. Use event.preventDefault() method to prevent your form from being submitted in the first place. So your Javascript code should be like this:
$(function() {
$("#sub").on("click",function (event){
event.preventDefault();
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
And in the backend upload.php page, you can access the uploaded file data using $_FILES, like this:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$name = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
// ...
}
?>
I have been trying to upload an image with AJAX but somehow it's not working. CodeIgniter always throwing 'You have not selected any file'.
Thanks in advance.
Here's my Controller -
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('url');
}
public function index() {
$this->load->view('upload/upload');
}
public function upload_file() {
$config['upload_path'] = './uploads/Ajax/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
$title=$this->input->post('title');
if (!$this->upload->do_upload('userfile')) {
echo $this->upload->display_errors()."<br>".$title;
}
else {
$data = $this->upload->data();
echo $data['file_name']." uploaded successfully";
}
}
}
/* end of file */
And here's the view
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX File Upload</title>
<script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js"> </script>
<script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js"> </script>
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
<p>
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" autocomplete="off">
</p>
<p>
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile">
</p>
<input type="submit" name="submit" id="submit">
</form>
<h2>Result</h2>
<span id="result"></span>
</body>
I have tested in Firefox 43, IE11 & Chrome 43
<script>
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajax({
url : '<?php echo base_url(); ?>upload/upload/upload_file',
type : 'POST',
secureuri :false,
fileElementId :'userfile',
data : FormData,
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
</script>
You need to add xhr function in ajax request
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
url: $(this).attr('action'),
data:formData,
cache:false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
you can use
$(document).on('submit','#form_id',function(){
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
});
no plugin required for this, for easiness you can use ajaxForm jquery plugin and just use
$('#form-id').ajaxSubmit({
// same config as ajax call but dont use data option right here
});
have a look on http://malsup.com/jquery/form/ to for more information about plugin
Use this
$("#upload-form").on('submit' ,function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: new FormData(form[0]),
dataType: 'json',
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function(data){
}
});
});
Use $.ajaxFileUpload instead $.ajax, this should work, if not please let me see your AjaxFileUpload.js
$(document).ready(function() {
$('#upload-form').submit(function(e) {
e.preventDefault();
if (typeof FormData !== 'undefined') {
$.ajaxFileUpload({
url :'./upload/upload_file/',
fileElementId : 'userfile', // your input file ID
dataType : 'json',
//
data : {
'title' : $('#title').val() // parse title input data
},
beforeSend: function () {
$("#result").html("Uploading, please wait....");
},
error: function () {
alert("ERROR in upload");
},
success : function(data) {
$('#result').html(data)
}
});
}
else {
alert("Your browser doesn't support FormData API!");
}
});
});
I am uploading files to a server, my code is running perfectly but i want to show progress bar till the image is being uploaded, i have seen various tutorials in core php but i want to accomplish it in codeigniter framework.
Below is my code:
<form name="posting_comment" id="posting_comment_<?=$row1['id']?>">
<input type="file" name="save_movie_<?=$row1['id']?>" id="movie_<?=$row1['id']?>" />
<input type="button" class="postbtn" id="submit_movie_<?=$row1['id']?>" value="Upload Video File" onclick = "return sendCareerData(<?=$row1['id']?>)"/>
</form>
<script type="text/javascript">
function sendCareerData(a)
{
var data = new FormData(document.getElementById('posting_comment_'+a));
data.append("file_m_id", a);
$.ajax({
type:"POST",
url:"<?php echo site_url('Dashboard/do_upload');?>",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success:function(data)
{
console.log(data);
}
});
}
</script>
Controller:
public function do_upload()
{
$lecture_id=$_POST['file_m_id'];
$output_dir = "./uploads/";
$fileName = $_FILES["save_movie_".$lecture_id]["name"];
move_uploaded_file($_FILES["save_movie_".$lecture_id]["tmp_name"],$output_dir.$fileName);
}
Use this before your success function
<script type="text/javascript">
function sendCareerData(a)
{
var data = new FormData(document.getElementById('posting_comment_'+a));
data.append("file_m_id", a);
$.ajax({
type:"POST",
url:"<?php echo site_url('Dashboard/do_upload');?>",
data:data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$("#loading").html('Please wait....');
},
success:function(data)
{
console.log(data);
}
});
}
</script>
and in your view add
<div id="loading"></div>
Read this for more https://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684