PHP file upload, sending formdata object - javascript

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,

Related

Upload file with ajax then list them

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 ?

.ajax for upload file and send text input to php, showed error message but upload success

I know this is a simple questions for experts here, but it has been bothering me for a few days. I am a beginners, and I think there is some problem in handling the data.
So my purpose here is to both fetched the file uploaded and email input by user, send it to upload.php, and then upload.php will return a reference ID, and then display it to user.
The problem I faced is instead of alert me with the reference number, it will show two errors:
Undefined index fileToUpload in xampp/htdocs...
There is an error in uploading file
But, the upload file is successful, I can see the uploaded file in my database and reference code is generated successfully.
If this two issues are solve, how can I display the reference code in the HTML part. Thanks!!! Any help is appreciate!
<form id="main-contact-form" class="main-contact-form" name="main-contact-form" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Address">
<input type="file" name="fileToUpload" id="fileToUpload" value="fileToUpload">
<input type="submit" value="submit" name="submit" class="btn btn-primary pull-left crsa-selected">
</div>
</form>
Here is my .ajax call that going to send email address and uploaded file to upload.php
$(document).ready(function () {
$("#main-contact-form").on('submit',(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
success: function()
{
alert("ajax success");
}
});
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.onload = function() {
alert(this.responseText);
};
oReq.open("get", "upload.php", true);
oReq.send();
}));
});
This is my upload.php
<?php
include("db.php");
$target_dir = "";
$target_file = "";
$target_dir = "submittedform/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$refId = "";
// upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded. <br/>";
$refID = !empty($_POST['refID']) ? $_POST['refID'] : time() . rand(10*45, 100*98);;
// echo "Reference ID: " . $refID . "<br/>";
echo json_encode("Reference ID: " . $refID . "<br/>");
#once file uploaded, the path and reference code will be updated, status will be set to 1
$sqlInsert = "INSERT INTO student(reference_id, upload_appli_form, status) VALUES ('$refID', '$target_file', '1')";
$qInsert = mysqli_query($db, $sqlInsert) or die("Error : ". mysqli_error($qInsert));
}
else
{
echo json_encode("Sorry, there was an error uploading your file. <br/>");
}
mysqli_close($db);
?>
Maybe it must be simpler? Like this?
And now it's async. So it will be valid for years :D
$(document).ready(function () {
$("#main-contact-form").on('submit', (function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function(result) {
alert(result); //your POST answer
});
}));
});

File and text upload from php page using ajax and store in mysql

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

Php error showing while accessing input type = file using jquery/ajax method

I need to access input type=file using jquery/ajax so that I can pass the value/file to php page. but It's showing me following error message :
Notice: Undefined index: file in D:\software installed\xampp\htdocs\contact-management
\editContactDetails.php on line 16
Is there any problem in my following code or Is there anyway to access it ?
My html code:
<form enctype="multipart/form-data">
<input type="file" name="file" id="file" class="file"/>
<input type="button" name="submit" value="Update Details" class="submit" id="UpdateDetails"/>
</form>
Jquery/Ajax code:
$(document).ready(function() {
$("#UpdateDetails").click(function() {
var fn = $('#family_name').val();
var cdid = $('#cdid').val();
var family_name = $('#family_name').val();
var given_name = $('#given_name').val();
var work_phone = $('#work_phone').val();
var mobile_phone = $('#mobile_phone').val();
var email = $('#email').val();
var email_private = $('#email_private').val();
var file_des_1 = $('#file_des_1').val();
var file = $('#file').val();
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: "editContactDetails.php",
data : {
'cdid' : cdid,
'family_name' : fn,
'given_name' : given_name,
'work_phone' : work_phone,
'mobile_phone' : mobile_phone,
'email' : email,
'email_private' : email_private,
'file_des_1' : file_des_1,
'file' : file
},
dataType: "html", //expect html to be returned
success: function(response){
$("#successUpdate").html(response);
//alert(response);
}
});
});
});
Php file Code:
//uoload first docuement with description...
$file_des_1 = $_POST['file_des_1'];
$did = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
//require file formate
$allowedExts = array("doc", "docx", "xls", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
//rename uploaded docuement
echo $doc_1 = $did.".".$extension;
$contacts_doc_directory = "contact_directory";
Try this for file upload
<form enctype="multipart/form-data" >
<input type="file" name="file" id="file" class="file"/>
<input type="button" name="submit" value="Update Details" class="submit" id="UpdateDetails"/>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#UpdateDetails").click(function() {
var formData = new FormData($('form')[0]);
alert(formData);
$.ajax({
url: 'editContactDetails.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
// myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
// beforeSend: beforeSendHandler,
// success: completeHandler,
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});//ajax
});
});
</script>
Before you start to work with data passed to a php script you should check that these data are actually passed to script... you can do it using isset() and empty() that checks if a value is set of variable you pass as an argument.
so your script becomes:
if (isset($_POST['file_des_1']) && !empty($_POST['file_des_1']) && isset( $_FILES["file"] ) && !empty( $_FILES["file"]["name"] )) {
//uoload first docuement with description...
$file_des_1 = $_POST['file_des_1'];
$did = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
//require file formate
$allowedExts = array("doc", "docx", "xls", "pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
//rename uploaded docuement
echo $doc_1 = $did.".".$extension;
$contacts_doc_directory = "contact_directory";
}

$.ajaxFileUpload successfully uploads file to a folder but wasn't able to pass values to be saved in the database

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"];

Categories