I don't get it, I have no redirects in the code whatsoever, yet the page is refreshed after the image gets uploaded to the folder and displayed in the page.
profile.php
<?php
echo "<img src='".$imagepath."?".mt_rand()."' id='theimgsource'>";
?>
<form method="post" enctype="multipart/form-data" id="pictureform" action="javascript:void(0)">
<label for="thefile" id="labelprofile">
<i class="fa fa-2x fa-camera"></i>
</label>
<input type="file" name="file" id="thefile" style="display: none;">
<div id="uploadMessage"></div>
</form>
jquery
$(document).ready(function() {
$("#thefile").change(function(event) {
event.preventDefault();
var formData = new FormData(document.getElementById("pictureform"));
$.ajax({
url: '../content/upload.php',
type: 'post',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(data);
$response = data;
console.log($response);
if (data) {
$('#uploadMessage').html("Image uploaded successfully!");
$('#theimgsource').attr("src", "../uploads/" + data);
} else {
$('#uploadMessage').html("There was an error uploading the image");
}
},
});
});
});
upload.php
<?php
session_start();
include_once "../includes/dbh.inc.php";
require_once "../includes/functions.inc.php";
$id = $_SESSION["userid"];
$file = $_FILES["file"];
$fileName = $_FILES["file"]["name"];
$fileTmpName = $_FILES["file"]["tmp_name"];
$fileSize = $_FILES["file"]["size"];
$fileError = $_FILES["file"]["error"];
$fileType = $_FILES["file"]["type"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = ["jpg", "jpeg", "png"];
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 500000) {
$fileNameNew = "profile" . $id . "." . $fileActualExt;
$fileDestination = "../uploads/" . $fileNameNew;
foreach (glob("../uploads/profile{$id}.*") as $match) {
unlink($match);
}
move_uploaded_file($fileTmpName, $fileDestination);
$id = $_SESSION["userid"];
$sql = "UPDATE users SET imagepath = ? WHERE users_id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo '<script>alert("There was an error with the SQL statement")</script>';
}
mysqli_stmt_bind_param($stmt, "ss", $fileDestination, $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
profileStatus($conn, $id);
echo $data = $fileDestination;
} else {
echo '<script>alert("File is too big!")</script>';
}
} else {
echo '<script>alert("There was an error uploading your file!")</script>';
}
} else {
echo '<script>alert("Wrong type of file!")</script>';
}
I am able to upload the picture in the uploads/ folder as well as the picture being displayed on the page, however as soon as it is displayed the page reloads itself. event.preventDefault() does not seem to work and as far as I can tell there are no redirects in this code. I have tried to look up other answers but nothing useful for my case.
Related
I want to upload User images via AJAX to PHP Database. I tried multiple tutorials and other examples but nothing worked for my code. The codes work when used without AJAX but since I don't wish my users to see the upload page and stay on the same page that's why the thought of adding AJAX to the code. So have been trying this code for the past few hours but nothing worked in my favor. The files are not getting uploaded nor the data in the database is getting updated.
file: test.php
<script>
function triggerClick(e) { document.querySelector('#profileImage').click(); }
function displayImage(e) { if (e.files[0]) {
var reader = new FileReader();
reader.onload = function(e){
document.querySelector('#profileDisplay').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]); } }
$(document).on('click',"#UploadImage", function(){
var fd = new FormData();
var profileImage = $('#profileImage')[0].files[0];
//fd.append('profileImage',profileImage);
var bio = document.getElementById( "bio" ).value;
$.ajax({
url:"include/Upload.php",
method:"POST",
data: fd,
contentType: false,
processData: false,
success:function(data){
alert(data);
if(data == "Login Successful") {
}
else {
alert(data);
}
}
})
});
</script>
File : Upload .php
<?php
session_start();
include('connection.php');
$msg = "";
$msg_class = "";
$Username = $_SESSION['Username'];
//echo var_dump($Username);
$conn = mysqli_connect("localhost", "root", "1234567890", "test");
$Status = stripslashes($_POST['bio']);
echo var_dump($Status);
$profileImageName = $Username. '-' . time() . '-' . $_FILES['profileImage']['name'];
echo var_dump($profileImageName);
$target_dir = "../UserImages/";
$target_file = $target_dir . basename($profileImageName);
if($_FILES['profileImage']['size'] > 200000) {
$msg = "Image size should not be greated than 200Kb";
$msg_class = "alert-danger";
}
// check if file exists
if(file_exists($target_file)) {
$msg = "File already exists";
$msg_class = "alert-danger";
}
// Upload image only if no errors
if (empty($error)) {
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file)) {
$sql = "UPDATE users_login SET Image='$profileImageName', Status='$Status' WHERE Username='$Username'";
echo var_dump($sql);
//header("location: profiles.php")
if(mysqli_query($conn, $sql)){
session_start();
$query="select * from $dbtable WHERE Username = '".$Username."' ";
echo $query;
$result2=#mysqli_query($connection,$query);
$row=mysqli_fetch_assoc($result2);
$_SESSION['ProfileImage']= $row['Image'];
print_r($_SESSION['ProfileImage']);
$_SESSION['Status']= $row['Status'];
$msg = "Image uploaded and saved in the Database";
$msg_class = "alert-success";
} else {
$msg = "There was an error in the database";
$msg_class = "alert-danger";
}
} else {
$error = "There was an error uploading the file";
$msg = "alert-danger";
}
}
?>
Removing those comments // worked and had to add another append line for bio and it worked. It wasn't working yesterday that's why I commented // on it. It's working properly now! Here's my new code that made it work...
var fd = new FormData();
var profileImage = $('#profileImage')[0].files[0];
fd.append('profileImage',profileImage);
var bio = document.getElementById( "bio" ).value;
fd.append('bio', bio);
Credits to: Ken Lee & charlietfl for their comments.
In my owner.vue, the admins are allowed to add owner into the table called "owner". For now, the owner's name can be successfully add into the database, while the column of it for image is empty. I wanted to make the admin able to add image into it together with the owner's name.
Owner.vue
//template
<v-text-field v-model="ob_person_name" label="Owner name" outlined required></v-text-field>
<input type="file" ref="ob_personal_document">
<v-btn text #click="createContact()">Confirm</v-btn>
//script
<script>
export default {
data: function () {
return{
ob_person_name:'',
ob_acc_type:""
}
},
methods: {
createContact: function(){
if(this.$refs.form.validate()){
this.ob_personal_document = this.$refs.ob_personal_document.files[0];
let formData = new FormData();
formData.append('ob_person_name', this.ob_person_name)
formData.append('ob_personal_document', this.ob_personal_document);
var owner = {};
formData.forEach(function(value, key){
owner[key] = value;
});
this.axios({
method: 'post',
url: 'http://www.example.com/process.php?action=create',
data: formData,
config: {
headers: {
'Content-Type':
'multipart/form-data'
}}
}).then(function (response) {
console.log(response)
this.newOwner.push(owner)
}).catch((error) => {
console.warn(error.message);
})
}
}
</script>
process.php
<?php
$host = '111.22.222.111';
$dbname = 'test';
$username = 'username';
$password = "password";
$conn = mysqli_connect($host, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed!" .mysqli_connect_error());
}
$result = array('error'=>false);
$action = '';
if(isset($_GET['action'])){
$action = $_GET['action'];
}
if($action == 'read'){
$sql = $conn->query("SELECT * FROM owners");
$owners = array();
while($row = $sql->fetch_assoc()){
array_push($owners, $row);
}
$result['owners'] = $owners;
}
if($action == 'create'){
$ob_person_name= $_POST['ob_person_name'];
$ob_personal_document = $_FILES['ob_personal_document'];
$sql = $conn->query("INSERT INTO owners (ob_person_name, ob_personal_document)
VALUES('$ob_person_name', '$ob_personal_document')");
if($sql){
$result['message'] = "Owner added successfully!";
}
else {
$result['error'] = true;
$result['message'] = "Failed to add owner";
}
}
The result of the image in phpMyAdmin shows "Array" as the image below.
the outcome of the ob_personal_document
I've solved the problem such by posting the image to the server's database and create folder directory and created another file.php
file.php
<?php
$ob_personal_document = $_FILES['ob_personal_document']['name'];
$valid_extensions = array("jpg","jpeg","png","pdf");
$extension = pathinfo($ob_personal_document, PATHINFO_EXTENSION);
if(in_array(strtolower($extension),$valid_extensions) ) {
if(move_uploaded_file($_FILES['ob_personal_document']['tmp_name'], "uploads/".$ob_personal_document)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
owner.vue
//template
<input type="file" id="ob_personal_document" ref="ob_personal_document" />
<button type="button" #click='uploadFile()' >Upload file</button>
//add another function after createContact
uploadFile: function(){
this.ob_personal_document = this.$refs.ob_personal_document.files[0];
let formData = new FormData();
formData.append('ob_personal_document', this.ob_personal_document);
this.axios.post('file.php', formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
if(!response.data){
alert('File not uploaded.');
}else{
alert('File uploaded successfully.');
}
})
.catch(function (error) {
console.log(error);
});
},
In this case, I've also added the name of the "image" to phpMyAdmin column to get the image that is same with the image's name in the storage.
My file input field keeps on resetting after every 1 seconds which gives an on pressing of submit button
Unexpected token < in JSON at position 1
i have also changed the original bootstrap to basic html to discover that the error is causing by ajax request which is used to get notification, It triggers itself at every 5 sec. I thought maybe its refreshing the web page that's why it shows no file selected after every time I select a file from my hard disk I increased the time to further 15 seconds but still error persists.
html code
<form enctype="multipart/form-data" method="post" id = 'u_excel_form'
name="fileinfo">
<div class="input-group-mb-3">
<div class="input-group-prepend">
<input type="text" placeholder="course code" name="subject_code"
id="u_subject_code">
</div>
</div>
<div class="input-group-mb-3">
<div class="input-group-prepend">
<input type="file" placeholder="Select file" id="file" name="file">
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success btn-lg btn-block" disabled
value="submit" name="submitExcel" id="u_submit_excel">
</div>
</form>
jquery code
$(document.body).on("click","#u_submit_excel",function(e)
{
e.preventDefault();
let property = document.getElementById("file").files[0]
if(property == undefined)
{
$("#u_errorDiv").addClass("show").children("span").text(`Please
select file`);
}else
{
var image_name = property.name;
var image_extension = image_name.split(".").pop().toLowerCase();
if($.inArray(image_extension , ['xlsx','xls']) == -1)
{
$("#u_errorDiv").addClass("show").children("span")
.text(`Caution :Only Excel files can be uploaded`);
}else
{
var form_id = $("#u_excel_form");
var u_course = $("#u_subject_code").val();
var formData = new FormData($('#u_excel_form').get(0));
formData.append("file",property);
formData.append("course",u_course);
formData.append($(this).attr('name'),$(this).attr('value'));
$.ajax({
url:"main.php?function=upload_excel",
method:"POST",
data:formData,
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
$("#u_errorDiv > span").removeClass("text-danger");
var query = `<i class="fas fa-spinner fa fa-spin "></i>`;
$("#u_errorDiv").addClass("show").children("span")
.html(`Questions are uploading
${query}`).addClass('text-info');
},
success:function(data)
{
$("#u_errorDiv > span").removeClass("text-info");
data = JSON.parse(data);
if(data[0] == 1)
{
$("#u_errorDiv").addClass("show").children("span")
.text(`${data[1]}`).addClass('text-success');
$("#u_excel_form input").not("input:submit").val("");
$("#u_submit_excel").attr("disabled","disabled");
}else{
$("#u_errorDiv").addClass("show").children("span")
.text(`${data[1]}`).addClass('text-danger');
},error:function(xhr, status, errorThrown)
{
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
cache:false
});
}
}
});
php code to upload file onto database
function fn_fetchExcelFileToServer() {
GLOBAL $fname,$uploadOk,$conn;
$msg = "";
$user_id = $_SESSION['user'];
$status;
$output = array();
$subject_id;
$subject_code =
$conn->real_escape_string(test_input($_POST['course']));
$sql ="select course_id from course_detail where course_code =
'".$subject_code."'";
$result = $conn->query($sql);
if($result->num_rows != 0)
{
$subject_id = $result->fetch_assoc()['course_id'];
$target_dir = "ExcelFiles/";
$actual_file_name = basename($_FILES["file"]["name"]);
$FileType = pathinfo($actual_file_name,PATHINFO_EXTENSION);
$target_file = $target_dir.uniqid($user_id).".".$FileType;
if(strcmp($FileType, "xls")==0 ||
strcmp($FileType,"xlsx")==0)
// Check if file is a actual excel file not
{
$uploadOk = 1;
}
else
{
$status = 0;
$msg.=" File is not Excel file. ";
$uploadOk = 0;
}
if (file_exists($target_file))
// Check if file already exists
{
$status = 0;
$msg.=" Sorry, file already exists. ";
$uploadOk = 0;
}
if ($_FILES["file"]["size"] > 500000)
// Check file size
{
$status = 0;
$msg.=" Sorry, file is too large. ";
$uploadOk = 0;
}
if ($uploadOk == 0)
// Check if $uploadOk is set to 0 by an error
{
$status = 0;
$msg.= "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else
{
if (move_uploaded_file($_FILES["file"]["tmp_name"],
$target_file))
{
$msg .= "The file ".basename( $_FILES["file"]
["name"]). " has been uploaded.";
$fname = $target_file;
$stmt = $conn->prepare("insert into
uploaded_excel(teacher_id, excel_id, file_name) values(?, ?,
?,)");
$stmt->bind_param("iss",$teacher,$excel_id,$file_name);
$teacher = $user_id;
$excel_id = $target_file;
$file_name = $actual_file_name;
$stmt->execute();
$stmt->close();
$status = 1;
}
else
{
$status = 0;
$msg .= "Sorry, there was an error uploading your file.";
}
}
}else{
$status = 0;
$msg .= "Please Verify Your Course Code ";
}
if($status == 1)
{
return $subject_id;
}else{
array_push($output,$status);
array_push($output,$msg);
print_r(json_encode($output));
die();
}
}
Error displayed is this :
Uncaught SyntaxError: Unexpected token < in JSON at position 1
at JSON.parse (<anonymous>)
at Object.success (interfacejQuery.js:1137)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
and please tell me why every time i select a file it flips to no file selected
actual output should be files uploaded successfully
Try changing your query variable to
// var query = `<i class="fas fa-spinner fa fa-spin "></i>`;
var query = ".fa-spinner";
$("#u_errorDiv").addClass("show").children("span").html("Questions are uploading");
$(query).addClass('text-info');
The syntax of addClass is
$(selector).addClass(classname))
I have a list of 4 images of an item.
One of them should show up in another page as a link from that page to the item page.
I want to be able to check a box so that this one will be the main pic and will show up in the category page.
this is the code of the form:
$all_pics_of_item = fetch_all_pics_of_item($item_id);
//print_r($all_pics_of_item);
if(is_array($all_pics_of_item))
{
echo '<ul>';
foreach($all_pics_of_item as $key=>$val)
{
if ($val['pics_main']=='yes')
{
$set_checked = "checked";
$action = true;
}
else
{
$set_checked = "";
$action = false;
}
echo '<li style="float: left;margin:10px;border: 1px solid #000;padding:10px;">';
echo '<img style="width:120px;height:120px;" src="../../gallery_images/thumbs/'.$val['pics_source'].'">';
echo '<br>'.$val['pics_name'];
echo '<br><div class="delet"><b>x</b></div>';
echo '<br><form method="post" action="update_main_pic.php" enctype="text/plain" >
Show in cat. page<input type="checkbox" class="myCheckbox" name="main" value="no"'.$set_checked.'&action='.$action.' data-picid="'.$val['pics_id'].'" data-itemid="'.$item_id.'" />
</form>';
echo '</li>';
}
echo '<ul>';
}
Here is the AJAX and script:
$(document).ready(function(){
$(':checkbox').click(function() {
$(':checkbox').not(this).removeAttr('checked');
var picid = $(this).attr('data-picid');
var itemid = $(this).attr('data-itemid');
var action = $(this).is(':checked');
//if((this).attr('checked',true))
//{
// var action = true;
//}
//else
// {
// var action = false;
// }
$.ajax({
url: "ajax_update_main_pic.php",
type: "POST",
data: "itemid=" + itemid + "&picid=" + picid + "&action=" + action,
timeout:5000,
dataType: "html",
beforeSend:function(){
},
error: function(){
alert('Problem !');
},
success: function(msg){
if(msg == 'no')
{
}
else
{
}
},
complete: function(){
}
})
});
}); //END READY
Here is the update function:
<?php
require_once "../../db.php";
require_once "../../functions.php";
if(isset($_POST['itemid']) && isset($_POST['picid']) && isset($_POST['action']))
{
$item_id = $_POST['itemid'];
$pic_id = $_POST['picid'];
$action = $_POST['action'];
}
else
{
header('location: upload_image.php');
die();
}
if($action == 'true')
{
$pic_show = 'yes';
}
else
{
$pic_show = 'no';
}
//print_r($pic_show);
function update_main_pic($item_id, $pic_id, $pic_show )
{
global $db;
try
{
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pics_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_items_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pics_main', $pic_show, PDO::PARAM_STR);
$stmt->execute();
return true;
}
catch(Exception $e)
{
return false;
}
}
$result = update_main_pic($item_id, $pic_id, $pic_show );
if($result == false)
{
die('Problem updating pics');
}
else
{
header('location: upload_image.php?iid='.$item_id);
die();
}
?>
I always get 'Problem updating pics'
It looks like only the checked checkbox is transmitted, while I want that the column PIC_MAIN will show "yes" if this is the one chosen and "no" foe all other pics
The issue lies with your binding.
You sql has the following name variables :pic_show , :pic_id and :item_id but you are binding :pics_main', :pics_items_id and :pics_id.
Change your binding to:
$sql = "
UPDATE pics SET
pics_main = :pic_show
WHERE pics_id = :pic_id AND pics_items_id = :item_id
";
$stmt = $db->prepare($sql);
$stmt->bindParam(':pic_id', $pic_id, PDO::PARAM_INT);
$stmt->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$stmt->bindParam(':pic_show', $pic_show, PDO::PARAM_STR);
The Data i am trying to insert is a blob or a file
This is for a school project and the lecturer said to insert it into the database for now.
This is what i have right now
function stop() {
cancelAnimationFrame(rafId);
endTime = Date.now();
$('#stop-me').disabled = true;
document.title = ORIGINAL_DOC_TITLE;
toggleActivateRecordButton();
console.log('frames captured: ' + frames.length + ' => ' +
((endTime - startTime) / 1000) + 's video');
embedVideoPreview();
};
function embedVideoPreview(opt_url) {
var url = opt_url || null;
var video = $('#video-preview video') || null;
var downloadLink = $('#video-preview a[download]') || null;
if (!video) {
video = document.createElement('video');
video.autoplay = true;
video.controls = true;
video.loop = true;
//video.style.position = 'absolute';
//video.style.top = '70px';
//video.style.left = '10px';
video.style.width = canvas.width + 'px';
video.style.height = canvas.height + 'px';
$('#video-preview').appendChild(video);
downloadLink = document.createElement('a');
downloadLink.download = 'capture.webm';
downloadLink.textContent = '[ download video ]';
downloadLink.title = 'Download your .webm video';
var p = document.createElement('p');
p.appendChild(downloadLink);
$('#video-preview').appendChild(p);
} else {
window.URL.revokeObjectURL(video.src);
}
if (!url) {
var webmBlob = Whammy.fromImageArray(frames, 1000 / 60);
url = window.URL.createObjectURL(webmBlob);
}
video.src = url;
downloadLink.href = url;
And this is how i am inserting it into the database from the same page i am also not to sure on where the video blob is also created.
<?php
require("connect.php");
$namey = video;
$up = mysql_query("INSERT INTO video VALUES ($namey)");
?>
Ok, so say you have an input for a user to upload a video...
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="VideoToUpload" />
<input type="submit" value="Upload Video" />
</form>
Then in your new upload.php you will want to process and save the file
$allowedExts = array("mp4", "mov");
$extension = end(explode(".", $_FILES["VideoToUpload"]["name"]));
if (($_FILES["VideoToUpload"]["type"] == "video/mp4") || ($_FILES["VideoToUpload"]["type"] == "video/quicktime")):
if($_FILES["VideoToUpload"]["error"] > 0):
echo "Error: " . $_Files["VideoToUpload"]["error"];
else:
move_uploaded_file($_FILES["VideoToUpload"]["tmp_name"], dirname(__FILE__) . "/FolderWhereIWantMyVideoSaved/" . $_FILES["VideoToUpload"]["name"]);
endif;
endif;
$VideoURL = "http://domain/and/path/to/FolderWhereIWantMyVideoSaved/" . $_FILES["VideoToUpload"];
$mysqli = new mysqli('ip.of.data.base', 'DatabaseName', 'Password', 'Username');
$stmt = $mysqli->prepare("INSERT INTO Videos (Name, Type, URL) VALUES (?,?,?)") or die ($mysqli->error);
$stmt->bind_param('sss', $_FILES["VideoToUpload"]["name"],$_FILES["VideoToUpload"]["type"], $VideoURL);
$stmt->execute() or die ($mysqli->error);
$stmt->close();
$mysqli->close();
Now the file is saved on the server, and the URL to that is in the database. So to display the video all you would then do is.
$mysqli = new mysqli('ip.of.data.base', 'DatabaseName', 'Password', 'Username');
$stmt = $mysqli->prepare("SELECT Name, Type, URL FROM Videos WHERE ID=?") or die ($mysqli->error);
$stmt->execute() or die($mysqli->error);
$stmt->bind_result($Name, $Type, $URL);
$stmt->store_result();
$stmt->fetch();
...
<video width="320" height="240" controls>
<source src="<?= $URL ?>" type="<?= $Type ?>">
Your browser does not support the video tag.
</video>
...
$stmt->close();
$mysqli->close();