I copied this code from stackoverflow it working fine when i upload multiple file through it. but i cannot send other parameter with it . it only upload the file but dont send the other parameter. i tried different way but i am unable to send the data.
My code is below but i dont send the second parameter of NewDir:foldername to my php file
This is my javascript code///////////
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%'); //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
$(document).ready(function(){
$('#files').change(function(){
var files = $('#files')[0].files;
var foldername = $('#Reciter_Name').val();
var error = '';
var form_data = new FormData();
var bar = $('.bar');
var status = $('#status');
var percent = $('.percent');
if(foldername == ''){
alert("Your Don't enter any name");
return false;
}
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['mp3']) == -1)
{
error += "Invalid " + count + " Mp3 File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/admin/upload", //base_url()
return http://localhost/tutorial/codeigniter/
method:"POST",
data:{form_data,NewDir:foldername},
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
// $('#uploaded_files').html("<label class='text-success'>Uploading...</label>");
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success:function(data)
{
$('#uploaded_files').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
});
This is my php code given below///////////
function upload()
{
sleep(3);
if($_FILES["files"]["name"] != '')
{
$output = '';
$config["upload_path"] = './uploads/audio/';
$config["allowed_types"] = 'mp3';
$config["overwrite"] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
{
$_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
$output .= '
<input type="hidden" name="url[]" value="'.base_url().'uploads/audio/'.$data["file_name"].'" />
<input type="hidden" name="surahname[]" value="'.$data["file_name"].'" />
'.$data["file_name"].'
';
}
}
}
echo $output;
}
So please tell me how i can pass data from php file.
/////////////////////////////////////////////////////////////////
You just need to add
form_data.append('NewDir',foldername);
Before assign form_data to ajax data variable
Related
I am trying to upload multiple files to a server. It works fine when there is one file, but as soon as there are multiple, I get "ERR_ACCESS_DENIED". Not sure if this has something to do with my permissions or just my naive code. Thanks in advance!
PHP:
session_start();
function outputJSON($msg, $code = 0, $status = 'error'){
header('Content-Type: application/json');
if ($code == 200 || $code == 201){
echo $code;
exit();
}
echo $msg . "||" . $code . "||" . $status;
die();
}
//ERROR CODES:
//200 - Upload and Processing successful;
//201 - Upload and Processing successful; - Rename made
//400 - Upload Failed
//511 - Not Authorized
//520 - Unknown
$tempDir = guidv4();
mkdir("disk/processing/" . $tempDir);
$putdir = 'disk/processing/' . $tempDir . '/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
outputJSON($_FILES["files"]["error"], 520, 'error');
} else {
if (file_exists($putdir . $_FILES["files"]["name"][$i])) {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], $putdir . $_FILES["files"]["name"][$i] . ' (1)');
outputJSON($tempDir, 200, 'done');
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], $putdir . $_FILES["files"]["name"][$i]);
outputJSON($tempDir, 201, 'done');
}
}
}
} else {
outputJSON('Empty Upload.', 400, 'error');
}
JS/JQ
$('#information').show();
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: 'uploadbackend.php', // point to server-side PHP script
dataType: 'application/json', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
xhr: function() {
var started_at = new Date();
xhr.upload.addEventListener( 'progress', function( e )
{
if( e.lengthComputable )
{
// Append progress percentage.
var loaded = e.loaded;
var total = e.total;
var progressValue = Math.round( ( loaded / total ) * 100 );
// Bytes received.
jQuery( '.recievedValue' ).html( '' );
jQuery( '.recievedValue' ).append( humanFileSize( loaded ) + ' / ' );
// Total bytes.
jQuery( '.totalValue' ).html( '' );
jQuery( '.totalValue' ).append( humanFileSize( total ) );
// Time Remaining
var seconds_elapsed = ( new Date().getTime() - started_at.getTime() )/1000;
var bytes_per_second = seconds_elapsed ? loaded / seconds_elapsed : 0 ;
var Kbytes_per_second = bytes_per_second / 1000 ;
var remaining_bytes = total - loaded;
var seconds_remaining = seconds_elapsed ? remaining_bytes / bytes_per_second : 'calculating' ;
jQuery( '.timeRemaining' ).html( '' );
jQuery( '.timeRemaining' ).append( seconds_remaining );
// Percentage.
$('#_explorer_progress').css("width", "" + progressValue + "%")
if (progressValue >= 100){
$('#information').html('Processing...')
}
}
}, false );
return xhr;
},
success: function (response) {
$('#information').html('Done.');
$('#upload').html('Uploaded! <i class="fa fa-check ml-5"></i>');
$('#upload').removeClass('btn-primary');
$('#upload').removeClass('btn-danger');
$('#upload').addClass('btn-info');
document.getElementById("upload").disabled = true;
$('#msg').html(response); // display success response from the PHP script
setTimeout(function () {
$('#upload').html('Start Upload <i class="fa fa-upload ml-5"></i>');
document.getElementById("upload").disabled = false;
$('#upload').addClass('btn-primary');
$('#upload').removeClass('btn-danger');
$('#upload').removeClass('btn-info');
$("#multifiles").val('');
}, 3000)
},
error: function (response) {
$('#information').html('There was a problem.');
console.log(response);
}
});
HTML:
<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
There is no response from the server except an "ERR_ACCESS_DENIED" error from the POST request.
When there is one file, it functions as expected.
I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}
I have music file to upload on database
and from view side I have addmore button for music input type file and I got that music's name like:
music1.mp3,music2.mp3,music3.mp3
After that I explode this above on controller file.
I don't know, is this correct?
$expaudio = explode(',',$audio);
$audioCount = count($expaudio);
if($audioCount == 0){ $audiolist = $audio; }
else{ $audiolist = $expaudio; }
for($i=0; $i<$audioCount; $i++){
//******************************* UPLOAD MUSIC ********************************//
$config['allowed_types'] = 'avi|mpeg|mp3|mp4|3gp|wmv'; //video and audio extension
$config['max_size'] = '40000000';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
//$video_name = random_string('numeric', 5);
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 10; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$video_name = $randomString;
$config['file_name'] = $video_name;
$config['upload_path'] = 'Users/'.$data['loginuserpage'].'/music/'.$project_url.'/audio';
//$config['allowed_types'] = 'gif|jpg|jpeg|png|doc|docx|ppt|pptx|pdf|txt|avi|mpeg|mp3|mp4|3gp|wmv'; // Image , video and audio
$this->load->library('upload', $config);
if (!$this->upload->do_upload($audiolist[$i]))
{
$error = array('error' => $this->upload->display_errors());
$vid_url = '';
print_r($this->upload->display_errors());
}
else
{
$upload_data = $this->upload->data();
$aud_name = $upload_data['file_name'];
$aud_type = $upload_data['file_type'];
$aud_url = $baseurl.$config['upload_path']."/".$aud_name;
}
//******************************* UPLOAD MUSIC ********************************//
}
My Ajax file
$("input[name='audio[]']").change(function()
{
var temp =[]
$("input[name='audio[]']").each(function(i, selected){
texts = $(selected).val()
temp.push(texts);
var jcat1 = temp.join(",");
alert(jcat1);
$('#audioarr').val(jcat1);
});
});
$('form#music').submit(function(e)
{
e.preventDefault();
var form = $(this);
/*var purl = form.find('#project_url').val();
if (purl.length < 8) {
$('p#purl').html('Please enter a url without space and specialchar');
return false;
}*/
var video = form.find('#video').val();
var trailer = form.find('#trailer').val();
dataString = $("form#music").serialize();
$.ajax({
url: '<?php echo base_url('video/creations/createmusic'); ?>',
type: "POST",
data: dataString,
data: new FormData(this),
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) { $("#success").html(data); }
});
});
You don't need to use for loop for uploading multiple files.
Since you are storing all file details in single array, use can use
$this->upload->do_upload('audio'); // input file name
You can access uploaded file details from
$data = $this->upload->data();
foreach($data as $audio) {
`// code goes here...`
}
I can comment with only first item in while loop, When I tried to comment with another item it's always display alert box You know you need to write a comment right?. I think it can't get comment text on another item in my loop, What's wrong with my code?
I've got this comment code from this link.
My code:
Ajax in index.php
<script type="text/javascript">
$(function () {
// Alert(event.timeStamp);
$('.new-com-bt').live('click', function (evt) {
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* When you click on the cancel button */
$('.bt-cancel-com').click(function () {
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function () {
$('.new-com-bt').fadeIn('fast');
});
});
// On post comment click
$('.bt-add-com').live('click', function (evt) {
var comment_on_id = $("input[name=comment_on_id]");
var theCom = $("textarea[name=comment-text]");
var theName = $('#name-com');
var theMail = $('#mail-com');
if (!theCom.val()) {
alert('You know you need to write a comment right?');
} else {
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post=' + comment_on_id.val() + '&name=' + theName.val() + '&email=' + theMail.val() + '&comment=' + theCom.val(),
success: function (html) {
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function () {
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
scroll.js in index.php
var ajax_arry=[];
var ajax_index =0;
var sctp = 100;
$(function(){
$('#loading').show();
$.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0){
$('#loading').hide();
for(var i=0;i<ajax_arry.length;i++){
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
$('#loading').show();
var ajaxreq = $.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page="+page,
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++]= ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
scroll.php
<?php
include('db.php');
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from infinitescroll order by id asc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$post_to_itemid = $row['id'];
$str.="<div class='data-container'><p>".$row['id']."</p><p>".$row['firstname']."</p><p>".$row['lastname']."</p>";
$str .= "<div class='new-com-bt'>
<span>Type something ..</span>
</div>
<div class='new-com-cnt'>
<br>
<input type='hidden' value='".$post_to_itemid."' name='comment_on_id'>
<textarea class='the-new-com' name='comment-text'></textarea>
<div class='bt-add-com'>Comment</div>
<div class='bt-cancel-com'>Cancel</div>
</div></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
}else{
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
?>
I m trying to save popup windows data in to database.but its throw error when i m trying pass data in queryString.Its just write "error".I dont know why its not call the update_clientstatus.php
Javscript :
function SaveNotes()
{
var notecontent = $("#txtPopNotes").val();
lookup(notecontent, globalNoteId);
overlay.appendTo(document.body).remove();
return false;
}
function lookup(inputstr, eleid) {
var inputString = inputstr;
// var row = parseFloat(eleId.substring(eleId.indexOf('_') + 1))+1;
var noteId = '#noteContent_' + eleid;
var editLinkId = '#editlink_' + eleid;
var saveLinkId = '#savelink_' + eleid;
var cancelLinkId = '#cancellink_' + eleid;
var txtBoxId = '#txt_' + eleid;
// var eleId = ele.id;
$.post("update_clientstatus.php", {queryString: ""+inputString+"", id: ""+eleid+"" }, function(data){
if(data=="success") {
alert("Status updated successfully");
$('.popup').hide();
var noteId = '#noteContent_' + globalNoteId;
$(noteId).html(inputstr);
$('.message').html('Status Updated successfully');
}
else
{
**document.write('error');**
}
});
} // lookup
PHP code(update_clientstatus.php)
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
}
try this
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
if ($query ) {
echo "success";
} else {
echo "error";
}
} else {
echo "error";
}