I want to upload photo with jquery-ajax in CodeIgniter. First I want to pass file to my controller for just check my AJAX call properly working or not.
My code is not posting anything to my controller. I posting my code here, please show me my fault
Here is my code
jQuery and my input of my view is here (profile_view.php)
<script type="text/javascript">
$(document).ready(function() {
$("#file1").on("change", (function() {
$("#showimage").fadeIn("slow").html('');
$("#showimage").fadeIn("slow").html('Plaese Wait...');
alert('hello');
$("#frm1").ajaxForm({
target: '#showimage',
success: function(response) {
alert(response);
},
error: function(err) {
alert(err);
}
}).submit();
}));
</script>
My input code is here
<div id="photoframe">
<form name='frm1' id="frm12" enctype="multipart/form-data" method="post" action="upload_photo">
<input type="file" name="file1" id="file1" style="visibility:hidden" />
</form>
<a style="color:white"><i class="fa fa-edit" id="img1">Edit Photo</i></a>
<div id="showimage" name='showimage'>
</div>
</div>
My controller is Here (upload_photo.php)
class Upload_photo extends CI_Controller {
function __construct() {
parent::__construct();
$this - > load - > helper(array('form', 'url'));
}
public
function index() {
$config['upload_path'] = '/user';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
if (isset($_POST['frm1'])) {
echo 'Image Uploaded';
echo "post".$_FILE['frm1'];
} else {
echo 'Image Upload Failed';
}
}
}
My output is : Image Upload Failed
I think there is problem with your request, You have not passed any data with that request, You can use following data method to pass data with ajax:-
$.ajax({
url: "post.php",
data: {
id: 123
},
type: "GET",
dataType : "json",
success: function( json ) {
// Do your code here for success
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
And you can not send image file with these AJAX request.
Please change your PHP code also, something like following :-
if (isset($_FILES['frm1'])) {
// Do your upload code here
}
else
{
echo 'Image Upload Failed';
}
This is the ajax call for non processed data (in your case upload images):
var form = $('frm12');
var formdata = false;
if (window.FormData){
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url: formAction,
data : formdata ? formdata : form.serialize(),
cache : false,
contentType : false,
processData : false,
dataType: "json",
type : 'POST',
resetForm: true,
})
.done(function(data) {
//returned response
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
Please note the "processData: false", this is needed to tel ajax to not act as a standard data transfer.
"By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false." from http://api.jquery.com/jquery.ajax/. You can find here explaination about the jquery.ajax settings.
Is worth to mention that if you want to make some checks before sending the data to the server (and I reccoment this) you can also use the "beforeSend: beforeSubmit," setting where "beforeSubmt" is a function that you can implement where you will make all the needed checks (e.g. allowed file type, allowed file size and more...). If something fails than the data will not be uploaded.
Related
I am trying to upload the image to the folder in codeginter using jquery. But I am not able to get what is the exact issue why the image is not getting upload and showing me message
You did not select a file to upload.
I am not able to get why the file is not selected to upload here. Her is my php code
public function add_new_book()
{
$image = $this->input->post('bookfile');
$img=$this->input->post('bookfile');
$config['upload_path'] = '/uploads';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('bookfile'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
}
}
And I write jquery code here
$( document ).ready(function() {
$("#btnsavebook").click(function(){
if($("#bookfileid").val() != ''){
if (typeof FormData !== 'undefined') {
var formData = new FormData($("#form-upload")[0]);
console.log("formdata:",formData)
$.ajax({
type: "POST",
url: "CreateBook/add_new_book",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success: function(result){
}
});
} }
});});
Anybody please tell me how can I achieve this process??
Thanks
Try this
View file
<html>
<head>
<title>Ajax Image Upload Using PHP and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="my_image" id="my_image" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
<h4 id='loading' >loading..</h4>
<div id="message"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "<?php echo base_url('test/hello'); ?>", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller {
public function __construct ()
{
parent::__construct();
}
public function index()
{
$this->load->view('test');
}
public function hello()
{
// print_r($_FILES['file']); die;
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'gif|jpg|png|jpeg'; // allowed file formats
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('my_image'))
{
echo $this->upload->display_errors(); // It will return errors if file not uploaded
}
else
{
echo "uploaded";
}
}
}
Source : https://www.formget.com/ajax-image-upload-php/
There seems to be a problem when I try to send my FormData with AJAX from my LTS server (not on my local machine). I suspect that FormData is not supported to all browser but it does work perfectly on my local machine with the same browser I used when I tried it on my server (LTS). I'm a bit lost here and don't know what to do.
To explain further:
index
<form class="image" enctype="multipart/form-data" accept-charset="utf-8" method="post">
<input id="image-value" data-id="{{id}}" name="{{picture}}" class="image-box-{{id}}" data-type="{{type}}" type="file" value="{{picture}}" />
<p id="{{id}}" class="label" >Update</p>
</form>
I need to get the file here and upload it into a server directory
script
$('[id="image-value"]').change(function(e) {
var data = new FormData();
var file_data = this.files[0];
data.append('file', file_data);
e.preventDefault();
$.ajax({
url: './someController/upload_picture/',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function(data){
if (data.success == true) {
console.log(data.image_name);
} else {
var error = data.error_message;
$(".question-message").fadeIn("fast").html(error);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("The following error occured: " + textStatus, errorThrown);
}
});
});
controller
function __construct() {
parent::__construct();
$config['upload_path'] = './data/picDir/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
}
function upload_picture() {
if ($this->check_authorization()) {
if ($this->ion_auth->get_user_id()) {
if ($this->upload->do_upload('file')) {
$data = $this->upload->data();
echo json_encode(array(
"image_name" => $data["file_name"],
"success" => true
));
} else {
echo json_encode(array(
"success" => false,
"error_message" => $this->upload->display_errors()
));
}
}
}
}
when triggered, the request just keeps on waiting for a response from the php controller which I think is not responding.
I believe your "echo json_encode..." should be in a response - something like $this->response(json_encode...). echo will not return a response to the ajax request. Please, check your framework or lib for the correct response and share it.
I'm trying to upload files through Ajax call and jQuery. Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element.
var tipoRecaudo = $('#tipoRecaudo'),
tipo_recaudo = tipoRecaudo.val(),
selectedIdsTipoRecaudo = [];
tipoRecaudo.select2({
ajax: {
dataType: 'json',
url: function () {
return Routing.generate('obtenerRecaudosTramite');
},
data: function (tipo_recaudo) {
return {
filtro: tipo_recaudo
}
},
results: function (data) {
var myResults = [];
$.each(data.entities, function (index, item) {
if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
myResults.push({
'id': item.id,
'text': item.nombre
});
}
});
return {
results: myResults
};
}
},
formatAjaxError: function () {
return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
}
}).change(function () {
var id = $(this).val(),
selectedData = tipoRecaudo.select2("data"),
htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
htmlTpl += '</td></tr></tbody></table>';
selectedIdsTipoRecaudo.push(id);
$('#recaudoContainer').append(htmlTpl);
});
$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
$("input:file").filestyle({
buttonText: "Seleccionar archivo",
iconName: "fa fa-upload",
buttonName: "btn-primary"
});
});
$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// Create a formdata object and add the files
var formData = $('#formRecaudosTramites').serialize();
$.each($('#formRecaudosTramites')[0].files, function (key, value) {
formData = formData + '&recaudos[]=' + value;
});
$.ajax({
url: Routing.generate('rpniSubirRecaudos'),
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
contentType: 'multipart/form-data',
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
}).done(function (data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
console.log('SUCCESS: ' + data.success);
} else {
// do something with error
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// do something with fail callback
// STOP LOADING SPINNER
});
});
What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object], what I'm doing wrong? Can any give me some working code for this stuff?
EDIT:
After reads the post referenced by user I change my code as the one before and now the error turns on:
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...
What is wrong there?
Note: Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge
i think this will help you,
var fd = new FormData();
//name is the key on the page of php to access the file
fd.append('name', $('#aob_file')[0].files[0]);
pass this fd object to your data field in ajax,
I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined. I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working.The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.
My code is below:
$(document).ready(function()
{
//for checking whether the file queue contain files or not
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files
function prepareUpload(event)
{
files = event.target.files;
alert(files);
}
$("#file-form").on('submit',uploadFiles);
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
//alert(key+' '+ value);
});
$.ajax({
url: 'module/portal/filesharing/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
console.log('ERRORS: ' + data.error);
}
}
});
function submitForm(event, data)
{
// Create a jQuery object
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();//controller stops here
// sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'update.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
}
});
</script>
Html:
<form id='file-form' action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filename" ><br>
<input type="submit" id='upload' value="Upload file">
</form>
My update.php:
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = 'module/portal/filesharing/upload/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer
Maybe your problem is this one, please check this out
how to get the uploaded image path in php and ajax?
I have followed a very helpful tutorial online to upload a file through AJAX in a HTML form.
Below is my HTML code then jQuery code.
HTML
<input type="file" id="myFile" name="myFile" />
<input type="button" id="upload" value="upload" />
<br />
<progress id="prog" value="0" min="0" max="100"></progress>
jQuery
$("#upload").on("click",function() {
$("#myFile").upload("xhr2.php", function(success) {
},$("#prog"));
});
How can I access the uploaded file in PHP to process the data and output any errors to the page?
EDIT
// data is optional
$.fn.upload = function(remote,data,successFn,progressFn) {
// if we dont have post data, move it along
if(typeof data != "object") {
progressFn = successFn;
successFn = data;
}
return this.each(function() {
if($(this)[0].files[0]) {
var formData = new FormData();
formData.append($(this).attr("name"), $(this)[0].files[0]);
// if we have post data too
if(typeof data == "object") {
for(var i in data) {
formData.append(i,data[i]);
}
}
// do the ajax request
$.ajax({
url: remote,
type: 'POST',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload && progressFn){
myXhr.upload.addEventListener('progress',function(prog) {
var value = ~~((prog.loaded / prog.total) * 100);
// if we passed a progress function
if(progressFn && typeof progressFn == "function") {
progressFn(prog,value);
// if we passed a progress element
} else if (progressFn) {
$(progressFn).val(value);
}
}, false);
}
return myXhr;
},
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false,
complete : function(res) {
var json;
try {
json = JSON.parse(res.responseText);
} catch(e) {
json = res.responseText;
}
if(successFn) successFn(json);
}
});
}
});
};
This is going to be a tough job to do, since your form upload and the file upload are happening in different requests. This being said the only way you can reference your file is to have it be uploaded before the form data. There are different ways you can reference your file, through a session, pass it as an additional queryString parameter to your form, use databases ( which would be dull ), it's really up to you. The main problem is that they are in separate requests and you need to establish a connection between them. Good luck!