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
Related
I just started with Ajax and also tried to find a solution for this.
Here is the problem:
I upload a .csv to a server. This works just fine. But after the upload "success" in the ajax call won't respond. Neither does complete or error. It shows nothing. Not even an empty alert. Just nothing. I also didn't find anything in the logs.
When I click the upload button without chosing a file to upload I get a response from success...
Here is the code:
upload.php
<?php
header('Content-type: application/json');
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$response[] ='';
if(move_uploaded_file($_FILES["file"]["tmp_name"],$target_file))
{
//$response['message'] = "File was uploaded!";
$response['message'] = csvToJson($target_file);
}
else
{
$response['message'] = 'Sorry, there was an error uploading your file.';
}
echo json_encode($response);
function csvToJson($file)
{
// open csv file
if (!($fp = fopen($file, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024",";");
// parse csv rows into array
$json = array();
while ($row = fgetcsv($fp,"1024",";")) {
$json[] = array_combine($key, $row);
}
// release file handle
fclose($fp);
// encode array to json
return $json;
}
?>
upload.js
$(document).ready(function(e)
{
// Submit form data via Ajax
$("#form").on('submit', function(e)
{
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'upload.php',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(response)
{
//var json = $.parseJSON(response)
alert(response);
},
error: function(error){
console.log("Error:");
console.log(error);
},
complete: function(response){
alert(response);
}
});
});
});
the form in index.php
<form id=form enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="Upload Excel" name="submit">
</form>
In the end I want a json back with the content of the uploaded file. But right now there is zero output if the file is uploaded.
Thanks for any advice!
EDIT for Solution:
The problem was something way different.
I had to format the output from csvToJson to UTF-8. After that I get a json as the respone.
Function for formatting to UTF-8 (got it from another post here)
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
Solution, but cannot mark it:
The problem was something way different. I had to format the output from csvToJson() in upload.php to UTF-8. After that I get a json as the respone.
Function for formatting to UTF-8 (got it from another post here)
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
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');
}
}
});
}
});
As I’m wrot in the title my aim is to upload a file via a form by AJAX and return the elements uploaded in a div.
This is form HTML:
<form method="post" action="add.php" enctype="multipart/form-data" id="form-add">
<input type="file" name="file" /><br />
<button type="submit">Envoyer</button>
</form>
This is the traitement that I used in PHP to make the AJAX request
if (isAjax()){
$dir_ext_img = 'img/type_files';
$req = $pdo->prepare('SELECT * FROM upload WHERE idU= ? ORDER BY idF DESC');
$req->execute([$idU]);
$file_being_up = $req->fetch();
?>
<div class="element_upload <?= $file_being_up->idF; ?>">
<img src="<?= $dir_ext_img .'/'. $file_being_up->extension; ?>.svg">
<a href="<?=$file_being_up->dir; ?>" class='name_file' target='_blank'><?= $file_being_up->nameF.'.'.$file_being_up->extension ; ?></a>
<a href="delete.php?idF=<?= $file_being_up->idF; ?>" class='delete'>Supprimer</a>
</div>
<?php
} else{
header('Location: account.php');
}
This is the function isAjax code:
function isAjax(){
return isset($_SERVER['HTTP_X_REQUESTES_WITH']) && $_SERVER['HTTP_X_REQUESTES_WITH'] == 'XMLHttpRequest';
}
This is my script JS in jQuery:
$('#form-add').on('submit', function (e) {
e.preventDefault();
var $form = $(this);
var formdata = (window.FormData) ? new FormData($form[0]) : null;
var data = (formdata !== null) ? formdata : $form.serialize();
var url = $form.attr('action');
$form.find('button').text('Chargement...');
$.ajax({
url: url,
type: $form.attr('method'),
contentType: false,
processData: false,
data: data })
.done(function(data, text, jqxhr){
$('.container').prepend(jqxhr.responseText);
$form.find('button').text('Envoyer');
});
});
The probleme is that I don’t have in return the response of the div that I’ve create in the script PHP, however I receive a full page with the new div inside.
Whereas I want only the previous div create in PHP to put it on the page where I want.
Is anybody know what can I do to have juste a new div with the file uploaded ?
Hi i'm currently developing a php page which has an file upload feature. my form sends over 2 hidden values which is an order id and sender id and the file. I have to use ajax as i can't make it refresh after upload. The file upload has to be in my upload/files folder and i need to store the order id , sender id and filename in mysql.My ajax is getting the order id and sender id when i serialize but not the file. i tried seraching on this site for solutions and came acrross FormData object way to no success and also few other methods. the error in my console is always undefined sender_id, file order_id. It doesnt get the values from the html form. Thanks for helping.
MY php, html form
<form method="POST " id="form1" name="form1" enctype='multipart/form-data' >
<input type="hidden" name="sender_id" value="<?php echo $_SESSION['user_session']?>">
<input type="hidden" name="order_id" value="<?php echo $_GET['oid']?>">
<?php //echo var_dump($sellerinfo);?>
<div>
<div>
<textarea name="comments" placeholder="Leave Comments Here..." style="width:800px; height:100px;"></textarea>
<div class="row">
<input type="file" id="file" name="fileupload">
<input type="reset" value="Reset">
<a type="file" href="" class="button" id="fileupload" name="fileupload"> UPLOAD FILE </a>
<br>
<a id="comment" href="" class="button">Post</a>
<input type="reset" value="Reset">
</form>
File.js (ajax file)
$("#fileupload").click(function(e){
alert("inside ajax");
var formData = $("#form1").serialize()
alert(formData);
var formData = new FormData();
var file_data = $('#file').prop('files')[0];
formData.append('file', file_data);
alert(formData);
$.ajax({
url: '../modules/Comment/fileupload.php',
type: 'POST',
dataType:"json",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
error: function (result) {
console.log(result);
alert('ERROR RUNNING INSERTSCRIPT');
},
success: function (result) {
alert(result)
if (result['result'] == true) {
alert("success");
order_id = document.form1.order_id.value;
$('#comment_logs').load("../modules/comment/file_logs.php?",{oid:order_id} );
}
else if (result['result'] == false) {
alert('ERROR');
}
},
});
});
My php script that is supposed to upload and insert data inside database.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require('commentclass.php');
$connect = new connect(); // new connect class OBJECT
$conn = $connect->get_connection(); // getting Connection from Connect Object
$sender_id=$_POST['sender_id'];
$order_id=$_POST['order_id'];
$Filename=basename( $_FILES['Filename']['name']);
define ('SITE_ROOT', realpath(dirname(__FILE__)));
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], '../../uploads/files/' . $_FILES['file']['name'])) ;
{
echo "The file " . basename($_FILES['Filename']['name']) . " has been uploaded, and your information has been added to the directory";
$sql = "INSERT INTO files(order_id,send_by,file_name) VALUES ('" . $order_id . "','" . $sender_id . "','" . $Filename . "')";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result) {
$data['result'] = true;
echo json_encode($data);
}
else
{
$data['result'] = true;
echo json_encode($data);
}
}
}
?>
Sorry for the long post, hope someone can help . Thanks in advance
I want to upload a file, send it to javascript formData object and than via ajax to some php script which will put the file into database. It works fine when i upload a file in profile php, send it to formData object in javascript and send it back to profile.php. Problem is that when i want to send formData object to some other php script which isn't profile.php, it doesn't work.
Here is my code:
profile.php
<form role="form" id="editUserProfile" method="post" action="" enctype="multipart/form-data">
<input type="file" id="filename" name="filename" class="file-input" accept="image/*"/></a>
<button type="submit">Save</button
</form>
javascript.js
$('#editUserProfile').validate({
submitHandler: function (form) {
var aFormData = new FormData();
aFormData.append("filename", $('#filename').get(0).files[0]);
$.ajax({
type: "POST",
url: "script.php",
data: aFormData,
success: function(data){
window.location.reload(true);
}
})
}
});
And than I want to check in some other php (script.php) script if file was uploaded.
if(is_uploaded_file($_FILES['filename']['tmp_name']) && getimagesize($_FILES['filename']['tmp_name']) != false){
$size = getimagesize($_FILES['filename']['tmp_name']);
$type = $size['mime'];
$imgfp = fopen($_FILES['filename']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['filename']['name'];
$maxsize = 99999999;
if($_FILES['userfile']['size'] < $maxsize ){
$dbh = new PDO("mysql:host=localhost;dbname=test", 'root');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO table (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
$stmt->bindParam(3, $size);
$stmt->bindParam(4, $name);
$stmt->execute();
}else{
throw new Exception("File Size Error");
}
}
Added to jQuery.ajax and it works now:
processData: false,
contentType: false,