Get file upload name and extension in JS - javascript

I have a upload image form which is being posted through some AJAX. I am trying to get the uploaded file name and extension to further process it into PHP file. I just can't get the correct function to retrieve Uploaded file name and extension or size. This is what i have tried. Any one please.
form
<div class="modal-body">
<form data-toggle="validator" action="api/update.php" method="put" enctype="multipart/form-data">
<input type="hidden" name="id" class="edit-id">
<div class="form-group">
<label class="control-label" for="title">Name:</label>
<input type="text" name="cat_name" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Image:</label>
<!-- <textarea name="description" class="form-control" data-error="Please enter description." required></textarea>-->
<input class="inputField" type="file" id="file" name="file" class="form-control" required>
<div class="help-block with-errors"></div>
</div>
<div>
<label>Type:</label>
<input type="radio" name="type" value="1" > Special
<input type="radio" name="type" value="0"> Ordinary
</div>
<br>
<div>
<label>Switch:</label>
<input type="radio" name="switch" value="1"> On
<input type="radio" name="switch" value="0"> Off
</div>
<div class="form-group">
<button type="submit" class="btn btn-success crud-submit-edit">Submit</button>
</div>
</form>
</div>
AJAX
$(".crud-submit-edit").click(function(e){
e.preventDefault();
var form_action = $("#edit-item").find("form").attr("action");
var name = $("#edit-item").find("input[name='cat_name']").val();
var image = $("#edit-item").find("input[name='file']").val();
var type = $("#edit-item").find("input[name='type']:checked").val();
console.log(type);
var switches=$("#edit-item").find("input[name='switch']:checked").val();
console.log(switches);
var id = $("#edit-item").find(".edit-id").val();
if(name != '' && type != ''){
$.ajax({
dataType: 'json',
type:'POST',
url: url + form_action,
data:{cat_name:name,cat_image:image ,cat_type:type,cat_switch:switches,id:id}
}).done(function(data){
getPageData();
$(".modal").modal('hide');
toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
});
}else{
alert('You are missing Name or type.')
}
});
});
update.php
$id = $_POST["id"];
$post = $_POST;
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
$uploaddir = "images/"; //Image upload directory
$filename = stripslashes($_FILES['cat_image']['name']);
$size=filesize($_FILES['cat_image']['tmp_name']);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['cat_image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
$sql = "UPDATE categories SET cat_name = '".$post['cat_name']."',cat_image='".$image_name."',cat_type = '".$post['cat_type']."' ,cat_switch='".$post['cat_switch']."' WHERE cat_id = '".$id."'";
$result = $con->query($sql);
$sql = "SELECT * FROM categories WHERE cat_id = '".$id."'";
$result = $con->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}

I do not know much about php but you can get file details in javascript like that code;
$("#showMe").click(function(){
var file=$("#myFile").val().replace(/C:\\fakepath\\/i, '').split(".");
console.log("File Name:"+file[0],"File Extension:"+file[1])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="myFile"/>
<button id="showMe">Show Me File Details</button>

To upload file using AJAX like you do, you should use FormData to collect all data from form and send it to php handler https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
similar topic How to use FormData for ajax file upload

Related

Issue posting form via AJAX

I have the following form which I then send upon submit via AJAX to insert to a MySQL DB through Ajax. All inputbox in form have their own Id and I get them all in my .php process file except the ones "cas" and "dat" that do not seem to go through the AJAX posting process.
The form:
<form id="form">
<div class="form-group">
<label class="lab" for="nm">id</label>
<input disabled type="text" id="id" name="id" class="form-control" placeholder="Id">
</div>
<div class="form-group">
<input type="text" class="form-control" name="cas" id="cas" value="2">
<input type="text" class="form-control" name="dat" id="dat" value="2017-11-30">
</div>
<div class="form-group">
<label class="lab" for="nm">Product</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM product_family order by product_type_id ASC","form-control","nm","nm","Select Product", "product_family", "product_family");?>
</div>
<div class="form-group">
<label class="lab" for="em">Win</label>
<input type="text" id="em" name="em" class="form-control allow_decimal" placeholder="Win">
</div>
<div class="form-group">
<label class="lab" for="hp">Drop</label>
<input type="text" id="hp" name="hp" class="form-control allow_decimal" placeholder="Drop">
</div>
<div class="form-group">
<label class="lab" for="ad">Currency</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM currency order by id ASC","form-control","ad","ad","Select Currency", "currency", "currency");?>
</div>
<button type="button" id="save" class="btn btn-success" onclick="saveData()">Save</button>
<button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>
</form>
I then have the following JavaScript code triggering the Insert upon "save data" click in order to post the different inputbox values to my .php processing file:
function saveData(){
var id = $('#id').val();
var name = $('#nm').val();
var email = $('#em').val();
var phone = $('#hp').val();
var address = $('#ad').val();
var casino = $("#cas").val()
var date = $("#dat").val();
$.post('server.php?p=add', {id:id, nm:name, em:email, hp:phone, ad:address, cas:casino, dat:date}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function viewData(){
$.get('server.php', function(data){
$('tbody').html(data)
})
}
Then I try to read my "$_post" values on the PHP side:
if($page=='add'){
try{
$id = $_POST['id'];
$nm = $_POST['nm'];
$em = $_POST['em'];
$hp = $_POST['hp'];
$ad = $_POST['ad'];
$casino_id = $_POST['cas'];
$date = $_POST['dat'];
}
I perfectly get all variables except the dat and cas posts that do no appear in the $_post list. Listing all $_Post the following way:
$myfile = fopen("LOGPOST.txt", "w") or die("Unable to open file!");
foreach ($_POST as $key => $value){
$txt= $txt."{$key} = {$value}//";
gives the following output: id = //nm = F&B Sales//em = 1000//hp = 500//ad = EUR//
What am I doing wrong?

I want to save multiple images path to a mysql database using file upload option? I am using a form which inputs other data to the database as well

This is my form code:
<form id="AddRoom" action="addRoomdb.php" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Home Renter User Name</label>
<input type="email" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter UserName">
<small id="emailHelp" class="form-text text-muted">This should be the username given when registering to the site.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">First Name</label>
<input type="text" name="firstname" class="form-control" id="exampleInputPassword1" placeholder="First Name">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Last Name</label>
<input type="text" name="lastname" class="form-control" id="exampleInputPassword1" placeholder="Last Name">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Price</label>
<input type="text" name="price" class="form-control" id="exampleInputPassword1" placeholder="Price">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Area</label>
<input type="text" name="area" class="form-control" id="exampleInputPassword1" placeholder="Area">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Available From</label>
<input type="date" name="availFrom" class="form-control" id="exampleInputPassword1" placeholder="Date from which the room is available">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Available To</label>
<input type="date" name="availTo" class="form-control" id="exampleInputPassword1" placeholder="Last date upto which the room is available">
</div>
<div class="form-group">
<label for="exampleSelect1">Room Type</label>
<select class="form-control" id="exampleSelect1" name="type">
<option>Single</option>
<option>Double</option>
<option>Triple</option>
</select>
</div>
<div class="form-group">
<label for="exampleTextarea">Description of Room</label>
<textarea class="form-control" id="exampleTextarea" name="description" rows="3"></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Photos</label>
<input type="file" class="form-control-file" id="exampleInputFile" name="image" aria-describedby="fileHelp" accept="image/gif, image/jpeg, image/png" multiple>
<small id="fileHelp" class="form-text text-muted">Maximum of 5 photos.</small>
</div>
<button type="submit" class="btn btn-primary">Add Room</button>
</form>
</div>
This is the addRoom.php page which i use to send the data to the database from the form...
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","","bnb");
if(!$con)
{
die('Could not connect');
}
mysqli_select_db($con, "bnb");
//check values are set
if(isset($_POST['username']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['price']) && isset($_POST['area']) && isset($_POST['availFrom']) && isset($_POST['availTo']) && isset($_POST['type']) && isset($_POST['description']) && isset($_POST['image'])){
$UserName =$_POST['username'];
$FirstName =$_POST['firstname'];
$LastName =$_POST['lastname'];
$Price =$_POST['price'];
$Area =$_POST['area'];
$AvailFrom =$_POST['availFrom'];
$AvailTo = $_POST['availTo'];
$Type =$_POST['type'];
$Description =$_POST['description'];
$image =$_POST['image'];
$query = "INSERT INTO bnb.rooms (UserName, FirstName, LastName, Price, Area, AvailFrom, AvailTo, Type, Facilities, Images) VALUES ('" . $UserName . "','" . $FirstName . "','" . $LastName ."','" . $Price . "','" . $Area . "','" . $AvailFrom . "','" . $AvailTo . "','" . $Type . "','" . $Description . "','" . $image . "')"; //sql query
$result = mysqli_query($con,$query); //execute
if($result){
header('location:index.php');
}
mysqli_close($con);
}
?>
I have tried many codes but the addRoom.php runs and the image get saved but not the image path from which i have selected...
can someone pls help...
For store image and save to database you done totally wrong.
1. Add enctype attribute in form tag
<form id="AddRoom" action="addRoomdb.php" method="post" enctype="multipart/form-data">
2. Use image name suitable for multiple
<input type="file" class="form-control-file" id="exampleInputFile" name="image[]" aria-describedby="fileHelp" accept="image/gif, image/jpeg, image/png" multiple>
Here we changed name="image" to name="image[]"
3. Use Global variable $_FILES to upload images
PHP file upload Tutorial
4. Now try and upload files for multiple input
For this many tutorials are available online, or refere below code.
<?php
if (isset($_POST['submit'])) {
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
$_FILES['file'] = $_FILES['image'];
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
// If file moved to uploads folder.
echo $j . ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j . ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j . ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
5. Get file path
While uploading files you can get file path with file name to store in database

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']."'");
}

php move_uploaded_file function not working but record save in database

i've design codes to upload image and data information in hosted server database. The record information save in table. But image not move to server folder. I also try rename() and Copy() but not working.
The strange thing is that i've designed four upload information forms(a,b,c and d) but d is not working. all 3 are working fine. same codes are in all files.
my codes are in files
d.php
<div class="container-fluid">
<!--Form 1-->
<div class="row">
<div class="col-md-6 center" id="shahster">
<div class="panel panel-default shadow">
<div class="panel-heading"><h3 class="panel-title">Shashter Form</h3></div>
<div class="panel-body">
<form class="form-horizontal" method="post" enctype="multipart/form-data" action="<?php $_SERVER["DOCUMENT_ROOT"] ;?>
/dashboard/other/other_sbt.php">
<div class="form-group">
<label class="control-label col-xs-3" for="name">Article Title Name</label>
<div class="col-xs-9"><input type="text" class="form-control" id="name" name="nametxt" placeholder="Enter Title Name" /></div></div>
<div class="form-group">
<label class="control-label col-xs-3" for="desc">Description</label>
<div class="col-xs-9"><textarea rows="3" class="form-control" id="desc" name="desctxt" placeholder="Description"></textarea></div></div>
<div class="form-group">
<label class="control-label col-xs-3" for="upload">Upload:</label>
<div class="col-xs-9"><input id="upload" class="file" type="file" name="upimage" data-min-file-count="1" /></div></div>
<div class="form-group">
<label class="control-label col-xs-3" for="type">Choose options</label>
<div class="col-xs-9">
<label class="checkbox-inline"><input type="checkbox" name="taksalitxt" value="taksali" /> Taksali</label></div></div>
<div class="clearfix"></div>
<div class="form-group">
<label class="control-label col-xs-3">Feature Product</label>
<div class="col-xs-9"><input type="checkbox" name="fproducttxt" value="fproduct"></div></div>
<div class="form-group">
<div class="col-xs-offset-3 col-xs-9">
<input type="submit" class="btn btn-primary" name="submit" value="Submit" />
<input type="reset" class="btn btn-default" value="Reset" /></div></div>
</form>
</div><!--Panel Body Close-->
</div><!--Panel default Close-->
</div><!--End of Col6 Form-->
</div><!--End of form Row-->
</div><!--End of Container-->
d_submit.php
ob_start();
//global $target_path;
include_once($_SERVER["DOCUMENT_ROOT"].'/dashboard/other/crudfrm.php');
$shaobj = new shashter();
if(isset($_POST['submit']) ){
$name1 = mysql_real_escape_string($_POST['nametxt']);
if(isset($_POST['taksalitxt'])){
$taksali = true;
}
else {
$taksali = false;
}
if(isset($_POST['fproducttxt'])){
$fproduct = true;
}
else {
$fproduct = false;
}
$desc = mysql_real_escape_string($_POST['desctxt']);
//*************IMAGE MANIPULATION
if(isset($_FILES['upimage'])){
$errors= array();
$file_name = $_FILES['upimage']['name'];
$file_size =$_FILES['upimage']['size'];
$file_tmp =$_FILES['upimage']['tmp_name'];
$file_type=$_FILES['upimage']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upimage']['name'])));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($file_tmp, $_SERVER['DOCUMENT_ROOT'].'uploadimg/other/full/'.$file_name);
//echo $moveResult;
echo $_SERVER['DOCUMENT_ROOT']."/uploadimg/other/thumb/".$file_name."<br>";
//exit();
echo "<br>Success";
}else{
print_r($errors);
}
}
}/*isset condition close*/
$thumb_path = "thumb/".$file_name;
$full_path = "full/".$file_name;
//*************IMAGE MANIPULATION END
if($moveResult) {
echo "File Uploaded Successfull!";
}else{
echo "ERROR: File not uploaded. Try again.";
// unlink($file_tmp); // Remove the uploaded file from the PHP temp folder
// exit();
}
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
// ---------- Include Universal Image Resizing Function --------
include_once($_SERVER["DOCUMENT_ROOT"]."/dashboard/image_resize_lib.php");
$target_file = $_SERVER['DOCUMENT_ROOT']."/uploadimg/other/full/$file_name";
$resized_file = $_SERVER['DOCUMENT_ROOT']."/uploadimg/other/thumb/$file_name";
$wmax = 200;
$hmax = 150;
//echo "<br><br>../../uploadimg/shashter/full/".$file_name;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function -----------
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
echo "The file extension is <strong>$fileExt</strong><br /><br />";
echo "The Error Message output for this upload is: $fileErrorMsg";
//#################################### SAVE RECORD USING CLASS LIBRARY ####################################
$register = $shaobj->createpro($name1, $desc, $taksali, $fproduct, $thumb_path, $full_path );
if($register){
// if everything is ok, try to upload file
echo "<script>alert('Product Added Successful')</script>";
header('Location: http://example.com/dashboard/admindashboard.php');
exit();
}else{
echo "<script>alert('Product Not Added Successful')</script>";
}
Add one check inside your if condition and put your code inside try catch block so that you will get the proper error messages. Try with this and edit as per your need :).
try {
if (isset($_POST['submit'])) {
if (isset($_FILES['upimage'])) {
$errors = array();
$file_name = $_FILES['upimage']['name'];
$file_size = $_FILES['upimage']['size'];
$file_tmp = $_FILES['upimage']['tmp_name'];
$file_type = $_FILES['upimage']['type'];
$file_ext = strtolower(end(explode('.', $_FILES['upimage']['name'])));
$extensions = array("jpeg", "jpg", "png");
if (in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed, please choose a JPEG or PNG file.";
}
if ($file_size > 2097152) {
$errors[] = 'File size must be excately 2 MB';
}
if (empty($errors) == true) {
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$dirPath = $_SERVER['DOCUMENT_ROOT'] . '/uploadimg/other/full/';
if (!file_exists($dirPath)) {
mkdir($dirPath, 0777, true);
}
$moveResult = move_uploaded_file($file_tmp, $dirPath . $file_name);
//echo $moveResult;
echo $dirPath . $file_name . "<br>";
//exit();
echo "<br>Success";
} else {
print_r($errors);
}
}
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
Hope this will help you.

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