how to upload file using ajax in codigniter - php

I have gone through many answers
How to upload file using ajax in codeigniter
File upload in codeigniter using ajax
which does not work with my code.
I want to upload word pdf img any sort of file using ajax.
This is my code:
Controller:
public function saveDetailData()
{
$rowId = $this->input->post('rowId',true);
$rowData = $this->input->post('rowData',true);
$rowColumn = $this->input->post('rowColumn',true);
$detailTableName = $this->input->post('detailTableName',true);
if($rowColumn == 'attachment'){
$filename2 = 'Query_'.rand(0,999999);
if( ! is_dir('uploads') ){mkdir('uploads',0777,TRUE); };
$path='uploads/queries/';
$imgtmpname=$_FILES['rowData']['tmp_name'];
$name = $_FILES["rowData"]["name"];
$ext = end((explode(".", $name)));
$fullpath= $path .$filename2.'.'.$ext;
$filename = $filename2;
move_uploaded_file($imgtmpname,$fullpath);
if ($ext <> '')
{
$fields = array(
'attachment' => $fullpath
);
}
else
{
$fields = array(
'attachment' => ''
);
}
}
$this->user_model->saveDetailData($rowId,$fields, $detailTableName);
echo "Successfully Saved";
}
View:
<?php echo form_open_multipart('editMatter');?>
<input onfocusout="saveDetailData1('<?php echo $detail->id; ?>',$(this).attr('name'),'attachment' )" type="file" id="attachment_<?php echo $detail->id; ?>" name="attachment_<?php echo $detail->id; ?>" value="">
<script>
function saveDetailData1(rowId,rowData,rowColumn) {
attachment = new FormData( $('#'+rowData)[0] );
$.ajax({
type: "POST",
url: "<?php echo base_url('user/saveDetailData')?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'rowId': rowId,
'rowData' :attachment,
'rowColumn' :rowColumn,
'detailTableName': 'tbl_mattersdetail',
},
dataType:"JSON",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(response){
//alert(response);
}
});
}
</script>

Try to modify the saveDetailData1 function like this :
function saveDetailData1(rowId,rowData,rowColumn) {
attachment = new FormData();
attachment.append('rowData', $('input[type=file][name="attachment_'+rowId+'"]')[0].files[0]);
$.ajax({
type: "POST",
url: "<?php echo base_url('user/saveDetailData')?>",
data: { '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'rowId': rowId,
'rowData' :attachment,
'rowColumn' :rowColumn,
'detailTableName': 'tbl_mattersdetail',
},
dataType:"JSON",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(response){
//alert(response);
}
});
}
This will skip the rowData function parameter, but instead directly select the file input as the rowData ajax parameter.

Related

getting error while uploading image via Ajax

im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);

Store clicks on each button separately in json

I am using jquery, php and json to store and update the clicks on a single download button. It's working flawlessly but now I need to be able to store and update the clicks from multiple download buttons and display them individually.
Can you guys give me a hand with this?
What I have so far is:
jQuery:
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
$.ajax({
url: "downloads.php",
success: function(response) {
if (response = 'success') {
// The counter file has been updated in the background, but we should update the results on screen to tell the user
var count = $('.small').html();
$('.small').html(parseFloat(count) + 1);
// Then redirect so that file can download
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
}
});
return true;
});
$.ajax({
url: "get-downloads.php",
success: function(data) {
var data = JSON.stringify(data, null, 4);
var data = $.parseJSON(data);
$('.small').html(data.count);
}
});
downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'] = $json['count'] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
get-downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
header('Content-Type: application/json');
echo json_encode($json);
?>
and the downloads.json
{"count":174}
try like this
for example for 3 button
<input type='button' name='btn1' class='download'/>
<input type='button' name='btn2' class='download'/>
<input type='button' name='btn3' class='download'/>
send name of button to server and show count in different .smallbtn1،.smallbtn2،.smallbtn3
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
//get name of button
var name= $(this).prop('name');
//==================
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
});
//===================
}
}
});
return true;
});
in downloads.php open json file
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.json
{"countbtn1":0,"countbtn2":0,"countbtn3":0}
this is my test and working for me

AJAX file upload to put data into data

I have this script that will upload multiple files and it will be retrieve by the controller.
Question
How can I put another data in the data: section in the AJAX request for example like this:
data: data + '&reference='+$('#ref').val(),
controller
function insertAttachment() {
$i = 0;
$referenceNo = $this->input->post('reference');
if(!isset($_FILES[$i]) ) {
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
for($i; $i <= 4; $i++) {
$counter = $_FILES;
while ( $i <= count($counter) ) {
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
$config['file_name']= 'IT2015' .'('. ($i+1) .').'. $xx[1];
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else {
$data = array('upload_data' => $this->upload->data());
$this->edit_development_model->insertonAttachments($data['upload_data'] , $referenceNo);
$i++;
}
}
}
}
}
Here is the script:
function EditUploadImage() {
var data = new FormData($('input[name^="edit_files"]'));
jQuery.each($('input[name^="edit_files"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax ({
type: 'POST',
data: data,
url: 'mis.php/edit_development_detailsControl/updateRequest',
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
//messagealert("Success","You're Request have been save successfully");
}
});
}
Hope this one help you.
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});

Multiple searchboxes via AJAX

I want to use several textboxes on the page which all have their own search query to fetch data from the database.
I have it working on 1 textbox but I can't get it to work for 2 or more textboxes.
This is my code:
php
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['text']) ? $_POST['text'] : FALSE);
$val2 = (isset($_POST['text']) ? $_POST['text'] : FALSE);
if ($val != null){
$where = " WHERE boekingsnummer LIKE '".$val."%'";
}
if ($val2 != null){
$where = " WHERE huiscode LIKE '".$val2."%'";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
ajax
$('#boekingsnummer_1').keyup(function(){
updateEmployeesText($(this).val());
});
$('#huiscode_1').keyup(function(){
updateEmployeesText($(this).val());
});
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
generate a string and pass it through url.
$('#huiscode_1').keyup(function(){
var text = '?val1='+$(this).val()+'&val2='$('#boekingsnummer_1').val();
updateEmployeesText($(this).val(text));
});
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php"+val,
cache: false,
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
like this. generate the string for every input fields u want and do the necessary checks before generating.GET the values on php script & process.hope this will work.

How to modify a PHP json_decode into a jquery.getJSON()?

I am a newer for study php and jQuery, I tried many times myself, but also not work well.
How to modify a PHP json_decode into a jQuery.getJSON()? I want modify all the PHPcode into javascript.
$json_data = file_get_contents("data.txt");
$data = json_decode($json_data, true);
if($data){
$num = 1;
foreach ($data as $result) {
?>
$.ajax({
url: "page2.php",
dataType: "html",
type: 'POST',
data: "value=<?php echo $result['name']; ?>",
success: function(data){
$("#result<?php echo $num; ?>").html(data);
}
<?php
$num++
}
}
?>
json tree:
[
{"name" : "name1"},
{"name" : "name2"},
{"name" : "name3"},
]
If you're sure the text file is json then the following should work as JSON is a subset of javascript.
<?php
$json_data = file_get_contents("data.txt");
echo "var json_data = $json_data;";
?>
for (var i = 0; i<json_data.length; i++) {
$.ajax({
url: "page2.php",
dataType: "html",
type: 'POST',
data: "value="+json_data[i].name,
success: function(data){
$("#result"+String(i+1)).html(data);
}
}

Categories