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!");
}
});
});
Related
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>
Actually i just trying to get all input data from serialize but i get the values in int type like age & id but unable to get value of name.
following is my code.
<html>
<body>
<form id ="form" method="post" class= "form">
Name<input type = "text" name = "name" /><br>
Age<input type = "number" name = "age" /><br>
ID<input type = "number" name = "id" /><br>
<input type = "submit" name = "submit"><br/>
</form>
<p id="result"></p>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#form").submit(function () {
var data = $("#form").serialize();
insertStudent(data);
return false;
});
function insertStudent(data) {
$.ajax({
url: 'process.php',
data: data,
type: 'POST',
dataType: 'json',
success: function (data, textStatus) {
$("#result").html(data);
},
error: function () {
alert('Not OKay');
}
});
}
});
</script>
</body>
</html>
process.php
print_r($_POST);// give error but if i try to get id then
print_r($_POST["id"])// print value
print_r($_POST["name"])// doesn't print name
$(document).ready(function () {
$("#form").submit(function (e) {
//e.preventDefault();
var data =$(this).serialize();
insertStudent(data);
return false;
});
function insertStudent(data) {
$.ajax({
url: 'process.php',
data: data,
type: 'post',
dataType: 'html',
success: function (data, textStatus) {
$("#result").html(data);
// console.log(data);
},
error: function () {
alert('Not OKay');
}
});
}
});
I'm trying to submit a single value as following?
HTML:
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" name="frmanalyse" id="frmanalyse">
{{ csrf_field() }}
<label for="marginsource" style="float: left; width:150px; text-align:left;">Margin Source</label>
<input type="file" name="marginsource" id="marginsource" >
<br />
</form>
script:
<script type="text/javascript">
$( "#frmanalyse" ).submit(function(event) {
$.post( "marginanalyser", {username: "medo ampir"}, function( data ) {
alert(data);
});
event.preventDefault();
});
in laravel routes:
Route::post('marginanalyser',function(Request $request){
echo $request->input('username');
$file = $request->file('marginsource');
echo 'File Name: '.$file->getClientOriginalName();
});
nothing shows in the message at all.
Change your JavaScript to use FormData as you aren't submitting the file
$( "#frmanalyse" ).submit(function(event) {
event.preventDefault();
var formData = new FormData();
formData.append('marginsource', $('#marginsource')[0].files[0]);
formData.append('username', "medo ampir");
$.ajax({
url : window.location.origin + "/marginanalyser",
type: "POST",
data : formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
});
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
I want to upload a file and send to server without refreshing page.
I have following line in my HTML file
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
upload.php file
if ($_FILES["mfile"]["error"] >0 )
{
echo "Error: " ;
}
else
{
if (file_exists("upload_email_files/" . $_FILES["mfile"]["name"]))
{
echo $_POST["file"]. " already exists. ";
}
else
{
$otp= move_uploaded_file('$_FILES["mfile"]"name"]','/../upload_templates/');
}
}
It's not working .Can anybody help me on this ?
It is not coming in upload.php and giving me error Illegal Invocation.
Thanks,
Shirish
in the case of "without refreshing page", you can use hidden iframe.
For reference,
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ ,
http://joekuan.wordpress.com/2009/06/12/ajax-a-simplified-version-of-file-upload-form-using-iframe/
Check this out I haven't tested it hope this will work http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader'));//remove [0]
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
//async: true,//Remove this line
//dataType: "JSONP",//Remove this line
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
Try this one :)
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
$(document).ready(function() {
$("#form-geninfo").submit(function(e)
{
e.preventDefault();
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
});