Not getting bootstrap file value using PHP - javascript

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

Related

AJAX call PHP same page and reload option values

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

Get file upload name and extension in JS

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

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.

upload audio mp3 file using ajax in codeigniter

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?

I am trying to auto update mysql database using ajax and no click button

My database is not updating dynamically. Am I missing something?
It was working before removing some field names and also it was updating the user records automatically. But now it seems some issue in updating dynamically.
Form javascript used for updating
<script type="text/javascript">
// JQUERY: Plugin "autoSumbit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
});
</script>
<script type="text/javascript" src="materialise/js/jquery-1.8.0.min.js"></script>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" >
<label for="firstname">Firstname: * <?php echo $firstname; ?></label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
update php used
<?php
// DATABASE: Connection variables
include_once("../php_includes/check_login_status.php");
// DATABASE: Clean data before use
function clean($value) {
global $db_conx;
$value = preg_replace('#[^a-z0-9. ]#i', '', $value);
$value = mysqli_real_escape_string($db_conx, $value);
return $value;
}
// FORM: Variables were posted
if (count($_POST)) {
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = "UPDATE users SET ".$col."='".$val."' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $result);
}
?>
below is the updated code working on my local...hope it will help you
did it without creating jquery plugin
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('input').blur(function() {
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
} else { // Load output into a P
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
});
});
</script>
</head>
<body>
<form id="ajax-form" class="autosubmit" method="POST" action="./php_parsers/ajax-update.php">
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<input type="text" name="firstname" value="<?php echo $firstname; ?>">
<label for="firstname">Firstname: * </label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-border-color prefix"></i>
<input type="text" name="lastname" value="<?php echo $lastname; ?>">
<label for="lastname">Lastname: *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-action-accessibility prefix"></i>
<input type="date" name="age" class="datepicker validate">
<label for="age">D.o.B *</label>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<i class="mdi-editor-mode-edit prefix"></i>
<label for="gender"><?php echo $sex; ?></label>
</div>
</div>
<input id="where" type="hidden" name="<?php echo $uname; ?>" value="<?php echo $uname; ?>" />
</form>
</body>
</html>
**Here’s the code example of a POST method call and AJAX database update –**
<div id="c">
<input id="text1" type="text" name="text1" />
<input id="submit" type="submit" name="submit" value="SAVE IT" />
</div>
<div id="cn">
</div>``
**Now we declare the JQuery code to make a POST call**
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function(){
var ths = this;
var str = $(ths).siblings("#text1").val();
$.post("saveData.php", {t:str}, function(value){
$(ths).parent("#c").fadeOut("fast");
$(ths).parent("#c").siblings("#cn").html(value);
});
});
});
</script>
**This code block receive value and update database**
$t = $_POST['t'];
$link = mysql_connect(servername, username, password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(databasename, $link);
// Insert the data
$query2="INSERT INTO p_a_j(scrap) VALUES('$t')";
$results2 = mysql_query($query2, $link)
or die(mysql_error());
if(mysql_affected_rows()>=1){
echo '<span>You entered'.$t.'</span>'.
'Database updated'.
'Try this again'; }

Categories

Resources