upload audio mp3 file using ajax in codeigniter - javascript

good day. I have a code which can upload image file but I don't know if this code is also work for uploading media file such as mp3. My project need to upload a media file but my code didn't work.
view
form
<form name="uploadform" id="uploadform" method="POST" enctype="multipart/form-data" >
<div class="form-group">
<label for="Title">Song Title</label>
<input type="text" class="form-control" id="title" placeholder="Title">
</div>
<div class="form-group">
<label for="Artist">Artist/Singer</label>
<input type="text" class="form-control" id="artist" placeholder="Artist/Singer">
</div>
<div class="form-group">
<label for="lyrics">Lyrics</label>
<textarea class="form-control" id="lyrics" placeholder="Lyrics"></textarea>
</div>
<div class="form-group">
<label for="Artist">Audio</label>
<input type="file" class="form-control" name="file" id="file" accept="audio/mp3">
</div>
<div class="form-group">
<span class="input-group-btn">
<button class="btn btn-primary" id="btn">UPLOAD</button>
</span>
</div>
</form>
view
javascript
$('#btn').click(function() {
var title = document.getElementById('title').value;
var artist = document.getElementById('artist').value;
var lyrics = document.getElementById('lyrics').value;
var file = $('#file').val();
$.ajax({
type: "post",
url: "<?php echo base_url('Admin/upload/')?>",
cache: false,
mimeType: "multipart/form-data",
contentType: false,
processData: false,
data: {
"title" : title,
"artist" : artist,
"lyrics" : lyrics,
"file" : file,
},
success: function(data){
try{
console.log(data);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
controller
Admin.php
public function upload()
{
$title = $this->input->post('title');
$artist = $this->input->post('artist');
$lyrics = $this->input->post('lyrics');
$attachment_file=$_FILES["file"];
$output_dir = "uploads/";
$fileName = $_FILES["attachment_file"]["name"];
move_uploaded_file($_FILES["attachment_file"]["tmp_name"],$output_dir.$fileName);
echo "File uploaded successfully";
}
that code gave me an error message.
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined index: file</p>
<p>Filename: controllers/Admin.php</p>
<p>Line Number: 35</p>
I do not know why the file is undefined index since the 'file' is exist on form tag.
my code is not working for uploading mp3. How can I make this problem works?

Related

Add image uploading function inside this existing ajax code

My code here works fine except image uploading. It inserts all data in database .
<input type="file" name="image2" class="file" id="imgInp"/>
But after adding file type input in php it is showing
Notice: Undefined index: image2 in C:\xampp\htdocs\upload\submit.php on line 18
How can I add image uploading function in my existing code.
<div id="form-content">
<form method="post" id="reg-form" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
</div>
// here is the problem
<input type="file" name="image2" class="file" id="imgInp"/>
//here is the problem
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...'); });
});
</script>
submit.php
<?php
$con = mysqli_connect("localhost","root","","table" ) or die
( "unable to connect to internet");
include ("connect.php");
include ("functions.php");
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
$post_image2 = $_FILES['image2']['name']; // this line shows error
$image_tmp2 = $_FILES['image2']['tmp_name'];
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments
(firstname,lastname,email,number,post_image) values('$fname','$lname','$email','$phno','$post_image2' ) ";
$run = mysqli_query($con,$insert);
?>
You can use FormData, also I suggest you can change the elements id of the form, now all of them have ('lname') Try this with your current:
In yout HTML, put an ID to your file input
<input type="file" name="image2" id="name="image2"" class="file" id="imgInp"/>
And change the id of the other input.
In your JavaScript:
var frmData = new FormData();
//for the input
frmData.append('image2', $('#image2')[0].files[0]);
//for all other input
$('#reg-form :input').each(function(){
if($(this).attr('id')!='image2' ){
frmData.append($(this).attr('name'), $(this).val() );
}
});
$.ajax( {
url: 'URLTOPOST',
type: 'POST',
data: frmData,
processData: false,
contentType: false
}).done(function( result ) {
//When done, maybe show success dialog from JSON
}).fail(function( result ) {
//When fail, maybe show an error dialog
}).always(function( result ) {
//always execute, for example hide loading screen
});
In your PHP code you can access the image with $_FILE and the input with $_POST
FormData() works on the modern browsers.If you want for older browser support use malsup/form plugin
Your Form
<form method="post" action="action.php" id="reg-form" enctype="multipart/form-data" autocomplete="off">
Javscript
<script type="text/javascript">
var frm = $('#reg-form');
frm.submit(function (ev) {
var ajaxData = new FormData(frm);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: ajaxData,
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
In php extract($_POST) to get all input data and $_FILE for files

Ajax submit Form serialized data in php are null

I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.

Not getting bootstrap file value using PHP

I am using bootstrap file upload. I have one form field called photo upload. I already inserted the file value in the database and moved it into a folder. Now I want to edit this photo. user edit the lastname and change photo means that time it will work fine,but user only change the last name that time it not working properly,because file name value is getting null, I am trying this method,How can I do this?
<?php
$sql = mysql_query("SELECT * FROM task_employee WHERE emp_email='".$_SESSION['email']."'");
while($edit = mysql_fetch_assoc($sql))
{
?>
<form class="form-horizontal" novalidate="novalidate" method="POST" id="newUserForm">
<div class="tab-content" style="margin:15px">
<div id="w2-account" class="tab-pane active">
<div class="form-group">
<label class="col-md-3 control-label">Last Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="lname" name="lname" value="<?php echo $edit['emp_lastname'];?>" placeholder="Enter your Lastname">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<span class="fileupload-preview"><?php echo $edit['emp_main_photo'];?></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file" value="<?php echo $edit['emp_main_photo'];?>">
</span><!--d42c4f0d9fcc1b1bff87fe8ba80b1605.jpg-->
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="submit" name="user-submit" id="user-submit">
</div>
</form>
<?php } ?>
<script type="text/javascript">
$(document).ready(function(){
$('#user-submit').click(function(event){
event.preventDefault();
if($('#newUserForm').valid()){
var formData = new FormData();
var formData = new FormData($('#newUserForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'php/profile_update.php',
type: 'POST',
data: formData,
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);// here i am getting null value for $filename
},
});
}
});
});
</script>
profile_update.php
<?php
$lstname=$_POST['lname'];//i am getting value here
$filename = basename($_FILES['file']['name']);// i am not getting value here
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_name= md5($filename.time()).'.'.$extension;
$update = mysql_query("UPDATE task_employee SET emp_lastname='$lstname',emp_main_photo = '$new_name' WHERE emp_id='".$_SESSION['emp_id']."'");
?>
Why don't you have write a condition over it like if user changed photo then you will get its name but if the user doesn't you will get that field empty.
if(isset($_FILES['file']) && !empty($_FILES['file']['name'])){
$filename = basename($_FILES['file']['name']);// i am not getting value here
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_name= md5($filename.time()).'.'.$extension;
$update = mysql_query("UPDATE task_employee SET emp_lastname='$lstname',emp_main_photo = '$new_name' WHERE emp_id='".$_SESSION['emp_id']."'");
}else{
$update = mysql_query("UPDATE task_employee SET emp_lastname='$lstname' WHERE emp_id='".$_SESSION['emp_id']."'");
}

404 Not Found on Jquery AJAX JSON PHP POST

I'm trying to POST some JSON data to a local host and I keep getting a 404 Not Found error which is strange because the php file is located in the correct location as specified in the script. I would appreciate any feedback from anyone who has experience with this. Am I getting this error because the the server can not locate the ajax.php file for some unknown reason?
<div class="container">
<div class="header">
<h3 class="text-muted">AJAX JSON Data</h3>
</div>
<div id="data-div">
<form method="post" action="api/ajax.php" class="ajax">
<p><label for="firstname" class="contact-input-text">First Name</label> <br/>
<input id="first-name" name="firstname" type="text" maxlength="30" autofocus /></p><p><label for="lastName" class="contact-input-text">Last Name</label> <br/>
<input id="last-name" name="lastname" type="text" maxlength="30" autofocus /></p>
<p><input type="submit" id="submit-button" class="contact-input-text" value="submit" /></p>
</form>
</div>
</div>
<script>
$('form.ajax').on('submit', function(){
var jsondata = {};
$(this).find('[name]').each(function(i, data){
console.log(data);
var that = $(this);
var key = that.attr('name');
var value = that.val();
jsondata[key] = value;
});
console.log(jsondata);
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType: 'json',
data: jsondata,
success: function(response){
console.log(response);
},
error: function(xhr){
console.log(xhr);
}
});
return false;
</script>
Here is the ajax.php file....
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$json_string = json_encode($_POST,JSON_PRETTY_PRINT);
file_put_contents($file,$json_string,FILE_APPEND);
}
?>
This is the directory structure :
index.html (contains the form input fields and the ajax request)
ajax.php
/styles
/images
have you ensure with correct url in ajax?
maybe not thi:
url: 'ajax.php'
but this:
url: 'api/ajax.php'

Image not send using javascript when submit form no refresh page

I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).

Categories

Resources