Code Igniter File Uploading Class with Jquery Ajax - javascript

So all I am trying to accomplish is simply upload a file with codeigniter using the File Uploading Class
For my controller I have the following code:
function do_upload()
{
$config['upload_path'] = './assets/productImages/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
}
}
And then my form is as follows:
$data['productImage'] = array(
"name" => "userfile",
"id" => "product_image",
);
// displays out as:
<input type="file" name="userfile" value="" id="product_image">
My javascript is as follows which uses an onchange action to trigger the upload process.
$("document").ready(function(){
$("#product_image").change(function() {
var path = $(this).val();
var dataString = 'userfile=' + path;
//alert(dataString); return false;
$.ajax({
type: "POST",
url: "/account/do_upload/",
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
});
});
When I run this code, I receive this message in the javascript alert
You did not select a file to upload.
What do I need to add to make this work? I'm guessing it has something to do with processing the upload through the javascript ajax.
*UPDATE DUE TO COMMENTS *
My form tag is as follows:
$data['newPostForm'] = array('id' => 'newPostForm', 'type' => 'multipart');
// And echoes out as :
<form action="http://myurl.com/index.php/account/submitPost" method="post" accept-charset="utf-8" id="newPostForm" type="multipart">

Your codeigniter code looks fine.
The problem is that you can't upload files directly through Ajax. You need to do it though an iframe.
This plugin here works a treat.
Or if you only need it to work in html 5 then this should do the treat
http://www.devbridge.com/projects/html5-ajax-file-upload/

Related

File upload not working in PHP , $_POST['file'] , not able to extract file

I have the following HTML code:
<form action="mail/filesend.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data" validate>
<div class="input-wrpr">
<input type="file" name="files[]">
</div>
<button type="submit">
Send File
</button>
</form>
And then the following file upload code in jQuery:
$(function () {
let files = null;
$('input[type="file"]').on('change' , (e) => {
files = e.target.files;
});
$('form').submit(function(e){
e.stopPropagation();
e.preventDefault();
let data = new FormData();
// files = $('input[type="file"]')[0].files;
$.each(files, function(key, value){
data.append(key, value);
});
console.log(data.getAll('0'));
// console.log(data);
$.ajax({
type: $(this).attr('method'),
url : $(this).attr('action'),
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
data : data
}).done(function(data){
// console.log(data);
if (! data.success) {
// console.log(data.errors);
/*for(let er in data.errors) {
console.log(data.errors[er])
}*/
console.log(data);
} else {
/* else condition fires if form submission is successful ! */
console.log(data.file);
}
}).fail(function(data){
console.log(data);
});
});
});
And the following PHP code for testing :
<?php
// You need to add server side validation and better error handling here
$data = array();
if(isset($_FILES['files'])) {
$data = array('file' => 'I a in if');
}
else {
$data = array('file' => 'I am in else');
}
echo json_encode($data);
?>
Now when i check my console i see that the PHP if condition is not passing , that is it is unable to detect:
isset($_POST['files'])
Why is this happening ? I have tried using isset($_FILES['files']), also I have tried renaming my html file input field to just files instead of files[] , but this does't seem to work , What am I doing wrong ?
I was following the tutorial HERE. But somehow the example I have created just does't work.
Try to print_r($_FILES) and check if it shows an array of file,
If it does, use the same key in $_FILES['same_key_here'] and it supposed to work,
Let me know if it doesn't
If you want to send files, do something like this.
This may help you.
var fileInput = $("#upload_img")[0]; // id of your file
var formData = new FormData();
formData.append("image_file",fileInput.files[0]); //'xmlfile' will be your key
Check in your php code like,
echo $_POST['image_file'];

Having a bit of trouble with my AJAX POST request to my PHP file

I'm trying to provide data to my MYSQL Database using Ajax, however, for some reason my PHP file is not reading the JSON array that I post to the file. Within the array I also have a file to store an image on my server as well as my database.
Javascript file
$(document).ready(function(){
// Give Data to PHP
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
//formData.append('tax_file', $('input[type=file]')[0].files[0]
var img = $('input[name=img]').prop('files')[0];
var name = img.name,
tmp = img.tmp_name,
size = img.size,
form = $('input[name=form-submit]').val(),
myName = $('input[name=my-name]').val(),
desc = $('input[name=description]').val();
// document.write(name + tmp + size);
var formData = {
'form-submit' : form,
'my-name' : myName,
'description' : desc,
'img' : name,
'tmp_name' : tmp,
'size' : size
};
// document.write(JSON.stringify(formData));
console.log(formData);
// process the form
$.ajax({
url : 'insert-bio.php', // the url where we want to POST
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
data : formData, // our data object
processData : false,
contentType : false,
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
My PHP file
include('../db.php');
$conn = new Database();
echo explode(",", $_POST['data']);
if(isset($_POST['form-submit'])){
// text data
$name = strip_tags($_POST['my-name']);
$desc = strip_tags($_POST['description']);
// picture stuff
$file = rand(1000,100000)."-".$_FILES['img']['name'];
$file_loc = $_FILES['img']['tmp_name'];
$file_size = $_FILES['img']['size'];
$file_type = $_FILES['img']['type'];
// folder for profile pic
$folder = "bio-pic/";
// new file size in KB
$new_size = $file_size/1024;
// make file name in lower case
$new_file_name = strtolower($file);
// final pic file
$final_file=str_replace(' ','-',$new_file_name);
// mysql query for form data
if(move_uploaded_file($file_loc,$folder.$final_file)){
$sql="INSERT INTO bio(img, name, description) VALUES('$final_file', '$name', '$desc')";
$conn->query($sql);
}
} else {
echo "Need data";
}
$query = $conn->query("SELECT * FROM bio");
$results=$query->fetchAll(PDO::FETCH_ASSOC);
$parse_bio_json = json_encode($results);
file_put_contents('bio-DATA.json', $parse_bio_json);
echo $parse_bio_json;
The console shows that I have made contact with my PHP file, but it simply has not read any data.
The error on the PHP file:
Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8
Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/WEBSITE/BIO/insert-bio.php on line 8 ArrayNeed data[]
I had the same issue back in the day. After doing lots of research I found out that JSON cannot have a property that holds a file value. However, you can follow this example. It worked great for me. Hope it helps :)
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
PHP
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Credit goes to -> jQuery AJAX file upload PHP

No file being uploaded while uploading multiple files using AJAX

I am trying to upload multiple files with only 1 AJAX request. But I am facing some problems and they are:
UPDATE
No file is being uploaded to the server
It seems to me that multiple AJAX requests are being made as AJAX is inside the for loop.
How to sort these problems?
HTML
<!--<form id="fileupload" method="POST" enctype="multipart/form-data">-->
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
<!--</form>-->
JS
$("#uploadfile").change(function(){
//submit the form here
//$('#fileupload').submit();
var files = $("#uploadfile")[0].files;
for (var i = 0; i < files.length; i++){
//alert(files[i].name);
var data = files[i].name;
$.ajax({
type:'POST',
url: 'mupld.php',
data: data
});
}
//var files = $('#uploadfile').prop("files"); //files will be a FileList object.
//alert(files);
//var names = $.map(files, function(val) { return val.name; }); //names is an array of strings (file names)
});
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
js at Question does not appear to upload File object, but File.name at var data = files[i].name; ? <!-- --> is not valid comment in javascript
Try using FormData()
$("#uploadfile").change(function() {
var files = $("#fileupload")[0];
$.ajax({
type:"POST",
url: "mupld.php",
data: new FormData(files),
processData: false,
contentType: false
});
});
Use it
AJAX File Upload plugin
<pre>
$("#uploadfile").change(function(){
$.ajaxFileUpload
(
{
url:'mupld.php',
secureuri:false,
fileElementId:'uploadfile[]',
dataType: 'html',
data:{},
success: function (data, status)
{
},
error: function (data, status, e)
{
}
}
);
});
</pre>

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

Html multiple file input - javascript access and delete files

Im trying to delete values from a html file input.
<input type="file" name="images" id="i1" class="imageup" multiple />
I cant seem to access the .files array to delete one of the values. I had tried using a hidden input type with the file value but i dont think this can be done....so im trying to access the input element to delete!
There is a fiddle below of all the code. There is a lot there to replicate the situation but the code controlling the delete event is about half way down the js.
http://jsfiddle.net/dheffernan/ryrfS/1
Does anyone have a method of accessing for example the 3rd inputted value of the multiple file upload and deleting?
The js code below- using .splice attempt.
var files=jQuery('#i'+inputid)[0].files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
var inputname= 3;
jQuery('#i'+inputid).splice(inputname, 1);
// no files are being deleted!!!
console.log('2nd test');
var files=jQuery('#i'+inputid)[0].files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
}
using html5 FormData solution:
Basically add the images to FormData, submit it using ajax and return the urls from where i uploaded them (i included the php for wordpress). I removed all data validation from js code and php code to keep it short + i still need a workaround for ie9 / older vers of browsers.
jQuery code:
jQuery(document).on('change', '.imageup', function(){
var id= jQuery(this).attr('id');
var length= this.files.length;
if(length>1) {// if a multiple file upload
var images = new FormData();
images.append('action', 'uploadimg'); //wordpress specific add functionname
jQuery.each(event.target.files, function(key, value ){
images.append(key, value);
});
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: images,
cache: false,
processData: false,
contentType: false,
success: function(data) {
var obj= JSON.parse(data);
jQuery.each(obj,function(key, value){
if(key!='errors') {
var ind = value.lastIndexOf("/") + 1;
var filename = value.substr(ind);
//do something here with filename
console.log(filename);
}
});
}//end of success function
}); //end ajax
}
});
php code wordpress, if not using wordpress change the above url, etc..
function uploadimg() {
$error = false;
$files = array();
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$upload_overrides = array( 'test_form' => false );
$url=array();
foreach($_FILES as $file){
$uploadimage= $file;
$movefile = wp_handle_upload( $uploadimage, $upload_overrides );
if ( $movefile ) {
if($movefile['url']) {
$url[]=$movefile['url'];
} else {
$url['errors'][]="error ".$movefile['file']." is not valid";
}
} else {
}
}
$url['errors'][]="error is not valid";
echo json_encode($url);
exit;
}
add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');
Edit
Try Blob , FileReader ?
see
https://developer.mozilla.org/en-US/docs/Web/API/Blob
https://developer.mozilla.org/en-US/docs/Web/API/File
How do I read out the first 4 bytes in javascript, turn it into an integer and remove the rest?

Categories