Hi Guys!
Im having isusses with my wordpress plugin. Im trying to upload a file through a form.
The problem is that I can't store my type="file" in the database.
I have some other functions where I put values like text inside my database without any problems.
I dont know if im supposed to change the custom.js function file or what to do...
Can u guys help me out?
thx for helping.
This is my Index.php
<form id="frmCreateFile" class="form-horizontal" action="javascript:void(0)" method="post"
enctype="multipart/form-data">
Select Image File to Upload:
<input id="file" type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
This is my Custom.js
jQuery("#frmCreateFile").validate({
submitHandler:function(){
var postdata = jQuery("#frmCreateFile").serialize()+"&action=crm_request¶m=create_file";
jQuery.post(crm_ajax_url, postdata, function(response){
var data = jQuery.parseJSON(response);
location.reload();
})
}
});
This is my Function.php
global $wpdb;
$param = isset($_REQUEST['param']) ? $_REQUEST['param'] : "";
if(!empty($param) && $param=='create_file'){
$customerId = '358';
// File upload path
$targetDir = VEOSOFT_CRM_DIR . "/uploads/";
echo $targetDir;
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = $wpdb->query("INSERT into wpwh_veosoft_crm_file (fileName, uploadDate, customer_Id) VALUES ('".$fileName."', NOW(),$customerId)");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
}
After clicking on submit my database is inserting a new row in my table with this value:
Id = 51
FileName = (empty)
Date = 2019-12-17
You cannot upload file using normal Ajax or in key value pairs. Files are uploaded using Multipart data.
Please try following Javascript
jQuery("#frmCreateFile").validate({
submitHandler:function(){
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
$.ajax({
url: crm_ajax_url,
type: 'post',
data: fd+"&action=crm_request¶m=create_file",
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
}
});
}
});
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am working with an ajax PHP upload, the upload works well without ajax jQuery. I went to Google to find more resources on it and adjusted my code several times but still get the same error at the backend that file is empty. This is my code.
At the frontend
<input class="input is-link" id="file" name="file" type="file">
<button id="sendImg" class="button">Send</button>
</form>
My jQuery code
$(function(){
$("#chatsCard").on('click', '#sendImg', function (e){
e.preventDefault();
//alert("test");
var filedata = $("#file").prop("files")[0];
var recipient = $("#uname").html();
//alert(filedata);
$.ajax({
type:'post',
url:'upload.php',
contentType:false,
processData:false,
cache:false,
dataType:'json',
data:{
//rec:recipient,
filedata
},
success:function(data){
alert (data);
}
});//ajax end
});//click end
});//doc end
Backend
<?php
session_start();
require("assets/db.php");
$logged = $_SESSION['logged'];
//This is always my ajax response.
if(empty($_FILES['file'])){
$response = "No picture selected";
echo json_encode($response);
exit;
}
$imgFolder = "media/";
$fileTpath = $_FILES['file']['tmp_name'];
$fileSize = filesize($fileTpath);
$info = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($info, $fileTpath);
$filetype = explode ("/",$filetype);
$filetype = $filetype[1];
$allowedFiles = array("jpg" , "png" , "jpeg");
//rename image.
$newName = uniqid(8);
$newName = "recipient".
$newName. "." . $filetype;
//check file size
if($fileSize > 21464568){
$response = "Picture is greater than 2MB, Resize and try again";
echo json_encode($response);
exit;
}
//check format.
elseif(!in_array($filetype, $allowedFiles)){
$response= "You are only allowed to upload jpeg,jpg or png";
echo json_encode($response);
exit;
}
//check for existence of file.
elseif(file_exists($imgFolder.$newName)){
$response = "Failed!!! Upload again!!!";
echo json_encode($response);
exit;
}
//move to folder.
else{
move_uploaded_file($fileTpath,$imgFolder .$newName);
$recipient = $_POST['rec'];
$time = date("d-M-y")." at ". date("h:ia");
$msg = "media";
//insert to messaging
$q = "INSERT INTO messaging(message,sender, receiver,time) VALUES(?,?,?,?)";
$stm = $conn->prepare ($q);
$stm->bind_param("ssss",$msg,$logged,$recipient,$time);
$stm->execute();
//insert media details
$q1 = "INSERT INTO media(sender,mediaName,mediaType) VALUES(?,?,?)";
$stm = $conn->prepare ($q1);
$stm->bind_param("sss",$logged,$newName,$fileType);
$stm->execute();
//json response
$response = "success";
echo json_encode($response);
exit;
}
?>
Since I removed the jQuery and the uploading works normally, I assumed the problem is not from the backend so I focused on the jQuery by tweaking it to these
//First change
var fd = new FormData();
var file = $("#file").props('files')[0];
var file data= fd.append("file",filedata);
//This still gives no picture selected.
//Second change
var fd = new FormData($("#mediaPic")[0])
//Passed fd as data but still the same response.
//Tried other stuffs I got on Google to get the image data but still d same response.
You just need to post FormData() object, Append method returns null. Datatype text is preferred. So the final jQuery code would be:
$(function(){
$("#sendImg").on('click', function (e){
e.preventDefault();
//alert("test");
var recipient = $("#uname").html();
var form_data = new FormData();
var file = $("#file").prop('files')[0];
form_data.append('file', file);
$.ajax({
url: 'upload.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
alert(data);
}
});//ajax end
});//click end
});//doc end
To add additional value with form_data, simple use before submitting
form_data.append("rec", "value");
We can generate and save locally a page as pdf with window.print(), but I want to know if I can save a page as pdf in a variable, exactly like window.print() generates a pdf, because I want to send it through ajax after. Thanks.
As i can understand your exact need this can be of your help.
HTML
<button onclick="document.getElementById('opepdf').click();">Read PDF</button>
<input id="opepdf" type="file" name="name" style="display: none;" onchange="PDFReader(event);"/>
Javascript
function PDFReader(e){
var file = e.target.files[0];
var pdfReader = new FileReader();// Create a File Reader
pdfReader.readAsText(file,'UTF-8');
pdfReader.onload = readerEvent => {
var PDFContent = readerEvent.target.result;
console.log( PDFContent );//PDF content in variable
}
}
Don't know if this cross browser or not but it does not need any js plugin.
More elaborate explanation about how you will be using this can improve the answers.
If you want to upload a file through ajax you can use other ways.
EDIT:
If you want to send PDF through ajax to your server use:
HTML:
<form>
Select PDF
<input id="opepdf" name="opepdf" type="file" /><br>
<div id="upload"></div><br>
<input type="submit" value="submit"/>
</form>
JAVA-SCRIPT: need jquery
//form Submit
$("form").submit(function(evt){
evt.preventDefault();
$("#upload").html("<img src='http://crabsheet.com/cs/wp-content/uploads/2012/08/capture-1.gif'>");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
$("#upload").html(response);
}
});
return false;
});
PHP-Serverside: there should be a "uploads" folder relative to script dir
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["opepdf"]["name"]);
$fileName = $_FILES['opepdf']['name'];
$fileType = $_FILES['opepdf']['type'];
$fileError = $_FILES['opepdf']['error'];
$fileContent = file_get_contents($_FILES['opepdf']['tmp_name']);
if($fileError == UPLOAD_ERR_OK){
//Processes your file here
if (move_uploaded_file($_FILES["opepdf"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["opepdf"]["name"]). " has been uploaded.";
} else {
echo "Error uploading your file.";
}
}else{
switch($fileError){
case UPLOAD_ERR_INI_SIZE:
$message = 'MAX UPLOAD SIZE Reached';
break;
case UPLOAD_ERR_FORM_SIZE:
$message = 'MAX FORM Upload Size Reached';
break;
case UPLOAD_ERR_PARTIAL:
$message = 'Could not finish Upload';
break;
case UPLOAD_ERR_NO_FILE:
$message = 'NO upload File';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = 'Servernot configured for file upload';
break;
case UPLOAD_ERR_CANT_WRITE:
$message= 'CANT WRITE';
break;
case UPLOAD_ERR_EXTENSION:
$message = 'Could not finish Upload.';
break;
default: $message = 'Could not finish Upload';
break;
}
echo json_encode(array(
'error' => true,
'message' => $message
));
}
?>
You know you can save a web page as pdf with window.print() so you want to catch the output of window.print() as var in javascript. But that's not your goal, right? Your end goal is to save your Html page as a pdf and send it through ajax. So you need to ask, is there any other way to save my Html page as pdf besides using window.print()? Now you are on the right track. To convert Html to pdf, you can use jsPDF's .html() PlugIn and html2canvas 1.0.0-alpha.12.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"
integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/"
crossorigin="anonymous"></script>
<script src="~/lib/html2canvas/html2canvas.min.js"></script></script>
<!-- html2canvas 1.0.0-alpha.11 up to v1.0.0-rc.1 works, current version may not work -->
<script>
function emailHtml() {
let pdf = new jsPDF('p', 'pt', 'a4');
pdf.html(document.body, {
callback: function () {
let obj = {};
obj.pdfContent = pdf.output('datauristring');
var jsonData = JSON.stringify(obj);
$.ajax({
url: '/api/yourapi',
type: 'POST',
contentType: 'application/json',
data: jsonData
});
}
});
}
</script>
You cannot get a value from window.print().
I have unsuccessfully been trying to send a Blob file (which is an .OBJ file type) to the server using AJAX. I want to be able to do this without using an input file field. I am making an online avatar creator, so the Blob file to be sent to the server is generated from the character that is initially imported into my Three.js scene. I have been able to send a Blob file that contains a String to the server and save this to a specified folder (which I am aiming to do with the Blob .OBJ file). I have tried converting the Blob to Base64 before sending it in a POST request, but this did not work. The size of the file that I am trying to send is 3MB.
Here is my JavaScript code for creating the Blob file and sending it to my PHP script on the server using AJAX.
//Create OBJ
var exporter = new THREE.OBJExporter();
var result = exporter.parse(child);
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
var reader = new FileReader();
reader.readAsDataURL(characterBlob);
reader.onloadend = function() {
formData.append('file', reader.result);
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
processData:false, // To send DOMDocument or non processed data file it is set to false
contentType: false, // The content type used when sending data to the server
}).done(function(data) {
console.log(data);
});
}
Here is my PHP script for handling the sent file.
<?php
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
?>
Any help would be much appreciated!
UPDATE 1: The var result = exporter.parse(child); is a String and whenever I print this variable to the console it takes a few minutes to load. Would the size of this String be a possible issue with trying to send it to the server?
UPDATE 2: This gets printed to the console after the PHP script has been executed, which makes me think that either nothing is being sent over to the server or the sent data is not being handled correctly by the PHP script.
Image Uploaded Successfully...!!File Name: Type: Size: 0 kBTemp file:
UPDATE 3: Here is a link to the file that I am trying to send.
http://www.filehosting.org/file/details/578744/CleanFemaleOBJ.obj
You can view this file in TextEdit/NotePad to view the String that I want to send. It is pretty much a text file with the .obj extension to convert it to that format so it can be opened in Maya.
UPDATE 4: I have now altered my JavaScript code so that the Blob is appended to the FormData and not the result of reader.readAsDataURL(characterBlob).
//Create OBJ
var exporter = new THREE.OBJExporter();
var result = exporter.parse(child);
//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('file', result);
$.ajax({
url: "ExecuteMaya.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
processData: false, // To send DOMDocument or non processed data file it is set to false
}).done(function(data) {
console.log(data);
});
Using the following code, I was able to upload the .obj file.
I had to increase my maximum upload size for it to work.
You may also think of increasing your maximum execution time as commented below, but I didn't have to.
For simplicity, I put everything in one file called form.php.
form.php
<?php
// good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);
// ini_set('max_execution_time', 300);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
echo "<b>Error:</b> " . $_FILES["file"]["error"] . "<br>";
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "uploads/" . $_FILES['file']['name']; // Target path where file is to be stored
if (move_uploaded_file($sourcePath, $targetPath)) { // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
} else {
echo "<span id='success'>Image was not Uploaded</span><br/>";
}
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<form action="form.php" method="post" enctype="multipart/form-data">
<label>File</label>
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
<div></div>
</body>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
// logic
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this), // important
processData: false, // important
contentType: false, // important
success: function (res) {
$('div').html(res);
}
});
});
});
</script>
</html>
So, first test to see if you can upload the .obj file using the code above.
As you are testing it out, have your browser's developer tool open. Monitor your Network/XHR tab [Chrome, Firefox] to see the request that gets made when you click Upload.
If it works, try using the same logic in your original code.
var formData = new FormData();
formData.append('file', result);
$.ajax({
url: "ExecuteMaya.php",
type: "post",
data: formData, // important
processData: false, // important
contentType: false, // important!
success: function (res) {
console.log(res);
}
});
Again, monitor the request made in your Network/XHR tab and look at what is being sent.
I'm trying to create little photo uploader with PHP and Ajax. So i'm not a php guy and i have some problems with that, always Something went wrong with your upload! status. But when i set this as form action i have success action. Can anyboody help?
HTML:
<form onsubmit="return submitForm()" method="POST" enctype="multipart/form-data">
<input type="file" name="pic" id="pic" multiple/>
<input type="submit" value="Upload" for="pic"/>
</form>
PHP:
<?php
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
and JS:
function submitForm() {
console.log("submit event");
$.ajax({
type: "POST",
url: "post_file.php",
enctype: 'multipart/form-data'
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
Much Thx!
You can't transfer file data through AJAX (like that anyway). It used to be impossible, and so iframe hacks were used to get around it, but now with HTML5 you can do it using FormData. Take a look at this: Using HTML5 file uploads with AJAX and jQuery
I have used ajaxfileupload upon form submission of my form. This is also for uploading purposes for image files. The image was successfully uploaded, however other data to be saved to database wasn't been included? Because it leaves my table fields blank, so I was thinking the values wasn't been passed to the category_save.php. I also observed that when I used the $.ajax({}) instead of $.ajaxFileUpload, the data were all successfully passed and saved in the database including the image file name but the actual file wasn't been uploaded at all. But when I used the $.ajaxFileUpload instead of $.ajax({}), it just work reverse, the file was uploaded but the values wasn't been saved in the database. What is the wrong with this? Here are my codes:
product_form.php
<form method="post" name="new_category" id="product_category" enctype="multipart/form-data">
<ul class="add_prod">
<li>Category Title:<input type="text" name="category[title]" id="cat_title" value="" placeholder="Title" /> </li>
<li>Category Description:<textarea rows="4" cols="40" name="category[description]"></textarea></li>
<li>Category Image:<input type="file" name="image_file" id="image_file" /></li>
</ul>
</form>
product1.js
$("#product_category").submit( function(){
event.preventDefault();
var data_category = $(this).serialize();
var image = $("#image_file").val();
$.ajaxFileUpload
(
{
type:"post",
url:"../wp-content/plugins/product_form/category_save.php",
secureuri:false,
fileElementId:'image_file',
dataType: "json",
data:data_category + "&image_file=" +image,
success: function (data)
{
if(data.notify == "Success"){
console.log(data.notify);
}
else{
return false;
}
}
}
);
});
product2.js
$("#product_category").submit( function(){
event.preventDefault();
var data_category = $(this).serialize();
var image = $("#image_file").val();
$.ajax({
type: "post",
url: "../wp-content/plugins/product_form/category_save.php",
dataType: "json",
data:data_category + "&image_file=" +image,
success: function(data){
if(data.notify == "Success"){
console.log(data.notify);
}
else{
console.log(data.notify);
}
}
});
});
category_save.php
<?php
//establish connection
$con = mysqli_connect("localhost","root","","ion2_emagi");
//on connection failure, throw an error
if(!$con) {
die('Could not connect: '.mysql_error());
}
$output_dir = "C:/Users/Employees/Dropbox/emagi/wp-content/plugins/product_form/img/";
$file_name = "image_file";
if(isset($_FILES[$file_name]))
{
//Filter the file types , if you want.
if ($_FILES[$file_name]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["image_file"]["tmp_name"],$output_dir. $_FILES["image_file"]["name"]);
}
}
//get the form elements and store them in variables
$category_values = $_POST["category"];
$image_url = basename($_POST["image_file"]);
$image_field = "image_url";
$data = array();
//unset($view_all_info['Password2']);
foreach($category_values as $field => $val){
$data[] = "`".$field."` = '".$val."'";
}
array_push($data,"`".$image_field."` = '".$image_url."'");
$sql = "INSERT INTO wp_product_category SET ".implode(',', $data);
$ret = mysqli_query($con,$sql);
if($ret){
$notification="Success";
}
else{
$notification="Failed";
}
echo json_encode(array('notify'=>$notification));
mysqli_close($con);
data field should have this format:
data: { data_category: data_category, image_file: image_file }
You are trying to pass it as a URL with parameters instead.
Then you have to retrieve it in PHP with POST by the name of the parameter. For example:
$category_values = $_POST["data_category"];