I can successfully upload a document in mysql blob (msword or pdf). Now I need help in downloading it.
Here is My download button code.
<form id="specificationdownload">
<input type="hidden" name="cusid" id="cusid" value = "<?php echo $row['id_stk']?>">
<button class="btn btn-success" name="downloadspec" type="submit">Download </button>
</form>
Here is my Ajax code which handles the download button form
//Specification download
$("form#specificationdownload").on("submit",function(e){
e.preventDefault();
jQuery.ajax({
url: "../data/stock.php?action=stock-specification-download",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR) {
console.log(2);
var filter = "<?php echo $id_stc ?>";
var tab_content_to_change = "#stock-sub-list";
jQuery(tab_content_to_change).load('/tasks/stock/stock-list.php?filter='+filter);
},
error: function(jqXHR, textStatus, errorThrown){
//Display error message to user
alert("An error occured when saving the data");
}
});
});
Here is my action
$CustomerID = $_POST['cusid'];
if(isset( $CustomerID ))
{
//Query
$prepare_query = "SELECT specificationsheet_name_stk,specificationsheet_type_stk,specificationsheet_size_stk, specificationsheet_stk FROM stock_stk
WHERE id_stk ='$CustomerID';";
$result = mysqli_query($mysqli_scs, $prepare_query);
$row = mysqli_fetch_array ($result);
//die(var_dump($row));
header("Content-length:" .$row['specificationsheet_size_stk']);
header("Content-type:" .$row['specificationsheet_type_stk']);
header("Content-Disposition: attachment; filename=".$row['specificationsheet_name_stk']);
return $row['specificationsheet_stk'];
exit;
}
The problem is when I click "Download" button, the file does not get downloaded. If I var_Dump the $row, It dump the array with right keys so object is there, but does not print.
Anybody know What I'm doing wrong.
Thank you.
Related
I'm trying to upload an image to a database using AJAX and PHP. When I click on a form's submit button, ajax should send the image's information to a php page where it will be inserted into a database. Here's the form for the image upload:
<form enctype='multipart/form-data' class='img-form'>
<input type='hidden' name='size' value='1000000'>
<input type='file' name='image' id='file-input' class='profile-file'>
<input type='submit' name='upload' value='Upload Image' id='submit-input'>
</form>
Then, when I click on the form's submit button/input type, I send an ajax request by calling a function I put the request in:
$(".img-form-container").on("click", "#submit-input", function(e) {
e.preventDefault();
setImage();
}
Here's the setImage() function:
function setImage() {
var sessid = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/profile/set_image.php',
type: 'POST',
data: {sessid: sessid},
success: function(data) {
console.log("successful image update");
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
}
Finally, in a separate file, I have the PHP code that recieves the AJAX request:
$allowed = ['image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'];
if (in_array($_FILES['image']['type'], $allowed)) {
$sessid= $_REQUEST['sessid'];
$target = "images/".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];
$q = "INSERT INTO profileimages (image, idUsers) VALUES ('$image', '$sessid')";
$r = mysqli_query($conn, $q);
} else {
echo "<p class='errormsg'>Only JPG and PNG files are permitted.</p>";
}
The problem is that I need the information needed for the $target and $image variables, but I don't know how to get it from javascript.
I already tried adding some of the PHP code into the JS function setImage() to send over to the PHP file, like so:
function setImage() {
<?php
if (isset($_POST['upload'])) {
$target = "images/".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];
}
?>
var target = "<?php echo $target ?>";
var image = "<?php echo $image?>";
var sessid = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/profile/set_image.php',
type: 'POST',
data: {sessid: sessid, image: image, target: target},
success: function(data) {
console.log("successful image update");
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
});
}
but it gives me this error:
<b>Notice</b>: Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>127</b><br />
<br />
<b>Notice</b>: Undefined index: image in <b>C:\xampp\htdocs\Real Website\profile.php</b> on line <b>128</b><br />
Basically, I need to get the information from the $target and $image variables ($_FILES['image'], etc.) into a javascript variable. Is there a way I can do this?
This system originally worked when I was building my site with plain PHP, but since I've added AJAX, I'm having trouble editing the code to make it work.
Let me know if it would help to add more code or if I made a mistake while posting the code in.
A good way to send a file to the server in js is to use the formData: follow this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
when you make
<?php
if (isset($_POST['upload'])) {
$target = "images/".basename($_FILES['image']['name']);
$image = $_FILES['image']['name'];
}
?>
you try to retrieve the absolute name of the file (here a string) then on the server you get this text as an image file that's why PHP cranks a undefined on
$_FILES["image"]
because the value received is a string and not a file.
$_FILES['image']['name'] contains the original name of the uploaded file.
Exple:
var form = $('form.img-form')[0];
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('size', '1000000');
//Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
now call ajax function
$.ajax({
url: 'includes/profile/set_image.php',
type: 'POST',
data: formData,
success: function(data) {
console.log("successful image update");
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
I'm trying to upload image on user registration via ajax. This is how it's look like the form + some fields for name, password and email which are working good.
<form method="post" class="registerForm" enctype="multipart/form-data" id="login-form">
<div class="form-group">
<label><b>Profile Image <span class="required">*</span></b></label>
<input accept="image/*" type="file" id="picture" name="picture" required>
</div>
<div class="clearfix">
<button type="submit" id="login" class="signupbtn">Sign Up</button>
</div>
</form>
I have found on another thread here on SO that I need to put this on my ajax script
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
And this is whole ajax
function submitForm()
{
var data = $("#login-form").serialize();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#login").html('<span class="glyphicon glyphicon-transfer"></span> sending ...');
},
success : function(data)
{
if(data=="registered")
{
}
}
});
return false;
}
And the server side for the picture part and the query
if(!empty($_FILES['picture']) && $_FILES['picture']['size'] >0 ){
$profilePic = $randomString. basename($_FILES['picture']['name']);
$uploadfile = $uploaddir .$randomString. basename($_FILES['picture']['name']);
if (move_uploaded_file($_FILES['picture']['tmp_name'], $uploadfile)) {
} else {
$error = "error\n";
}
}else{
$error ='Please add your Picture!';
}
var_dump($_FILES['picture']);
try
{
$stmt = $db_con->prepare("SELECT * FROM users WHERE email=:email");
$stmt->execute(array(":email"=>$email));
$count = $stmt->rowCount();
if($count==0){
$stmt = $db_con->prepare("INSERT INTO users (picture) VALUES (:picture)");
$stmt->bindParam(":picture",$profilePic);
if($stmt->execute()) {
echo "registered";
}
else { echo "Query could not execute !"; }
}
else{ echo "1"; }
}
catch(PDOException $e){
echo $e->getMessage();
}
I've removed other fields in order keep the code simple as much as possible. All fields got inserted and saved in database except the image name.
What can be the problem? No errors at all. I've got registered on the console and NULL for var_dump($_FILES['picture'])
jQuery processes the data as a string if you don't use proccessData: false. Bellow code will work just fine. Also included some comments in code
$(document).ready(function (e){
$("#login-form").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "registration.php",
type: "POST",
data: new FormData(this), // Data sent to server
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=="registered"){}
},
error: function(){}
});
}));
});
You must set the contentType option to false, so jQuery won't add a Content-Type heade also set processData flag set to false otherwise jQuery will try to convert your FormData into a string, which will fail.
So ajax code will look like
$(".signupbtn").click(function(e){
e.preventDefault();
var form = new FormData(document.getElementById('picture'));
//append files
var file = document.getElementById('picture').files[0];
if (file) {
form.append('picture', file);
}
$.ajax({
type : 'POST',
url : 'registration.php',
data : form,
contentType: false,
processData: false,
success : function(data){}
});
});
My code is about submitting a multipart form, through $.ajax, which is successfully doing it & upon json_encode in submit.php , its giving me this :
{"success":"Image was submitted","formData":{"fb_link":"https:\/\/www.google.mv\/",
"show_fb":"1",
"filenames":[".\/uploads\/homepage-header-social-icons\/27.jpg"]}}
Can someone explain me, in submit.php, how can i extract values from formData, to store in mysql table ? I have tried, so many things including :
$fb_link = formData['fb_link'];
$show_fb = formData['show_fb'];
and
$arr = json_encode($data);
$fb_link=$arr['fb_link'];
and
$fb_link = REQUEST['fb_link'];
$show_fb = REQUEST['show_fb'];
but, nothing seems to work ? Any Guesses ?
Thanks
update :
JS code on parent-page is :
$(function()
{
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
$('form#upload_form').on('submit', uploadFiles);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
//var data = new FormData($(this)[0]);
$.ajax({
url: 'jquery_upload_form_submit.php?files=files',
type: 'POST',
data: data,
//data: {data, var1:"fb_link" , var2:"show_fb"},
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'jquery_upload_form_submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
});
UPDATE CODE OF - submit.php :
<?php
// Here we add server side validation and better error handling :)
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = './uploads/homepage-header-social-icons/';
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename($file['name']))) {
$files[] = $uploaddir . $file['name'];
//$files = $uploaddir . $file['name'];
}
else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your image-files') : array('files' => $files);
}
else {
$data = array(
'success' => 'Image was submitted',
'formData' => $_POST
);
}
echo json_encode($data);
?>
If you're using POST method in ajax, then you can access those data in PHP.
print_r($_POST);
Form submit using ajax.
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
You can access the data on PHP
$json = '{"countryId":"84","productId":"1","status":"0","opId":"134"}';
$json = json_decode($json, true);
echo $json['countryId'];
echo $json['productId'];
echo $json['status'];
echo $json['opId'];
If you want to access file object, you need to use $_FILES
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];
This problem is different in terms that :
1. Its sending MULTIPLE files, to upload
2. Contains a SELECT
3. Contains an INPUT
So, images are serialized & sent via GET . And, rest FORM data is being sent via POST. So Solution is :
var data = new FormData($(this)[0]);
inside : function uploadFiles(event){}
And in submit.php :
print_r($_POST);
print_r($_GET);
die();
This will give you both values. Then comment these & as per the Code, make these changes :
$filename_wpath = serialize($files);
$fb_link = $_POST['fb_link'];
$show_fb = $_POST['show_fb'];
$sql = "INSERT INTO `tblbasicheader`(fldFB_image, fldFB_link, fldHideShow)
VALUES('$filename_wpath','$fb_link','$show_fb')";
mysqli_query($db_conx, $sql);
Works like Charm ! :)
I am using jQuery ajax to upload files. When I clicked upload button,it fails and the error section of ajax is showing Uncaught TypeError: Cannot read property 'length' of undefined. I have checked the code and found that alerting the jqXHR shows success in the first ajax call,but the ajax call in submitForm() is not working.The controller stops before the $.each(event,data) and it shows the above error in the console.Please help me.
My code is below:
$(document).ready(function()
{
//for checking whether the file queue contain files or not
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files
function prepareUpload(event)
{
files = event.target.files;
alert(files);
}
$("#file-form").on('submit',uploadFiles);
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
//alert(key+' '+ value);
});
$.ajax({
url: 'module/portal/filesharing/upload.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
console.log('ERRORS: ' + data.error);
}
}
});
function submitForm(event, data)
{
// Create a jQuery object
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();//controller stops here
// sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'update.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
}
});
</script>
Html:
<form id='file-form' action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="filename" ><br>
<input type="submit" id='upload' value="Upload file">
</form>
My update.php:
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = 'module/portal/filesharing/upload/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
If you want it works on cross-browser, i recommend you use iframe like this http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html
Or there is some jquery modules using flash for upload they are also good option for older version of internet explorer
Maybe your problem is this one, please check this out
how to get the uploaded image path in php and ajax?
I am writing code to test AJAX image and data upload. However, the Ajax seems to return an error stating that the input is not valid:
Syntax error: unexpected end of input
The script and HTML are as follows
<input type="file" name="vdofile" id="file" />
<input type="text" id="name" />
<button id="send">Send</button>
$("#send").click(function(){
var form = new FormData();
form.append('vdofile',$("#file").prop("files")[0]);
form.append('name', $("#name").val());
$.ajax({
url: 'upload.php',
type: "POST",
data: form,
dataType: 'json',
contentType: false,
processData: false,
success: function(data)
{
alert(data.message);
},
error: function(xhr, status, error)
{
alert('An error occured.. ' + xhr.responseText + '..' + error );
}
});// ajax
}); // function
The test PHP is as follows:
header("Content-Type: application/json");
if(isset($_FILES['vdofile']) && isset($_POST['name']))
{
$result = array(
'message' => 'both data and file received'
);
}
else {
$result = array(
'message' => 'one of parameter missing'
);
}
return json_encode($result);
Your PHP is returning an empty response. return doesn't print anything.
print json_encode($result);
should work better.