i have the following html code:
<form class="dropzone" id="msform" enctype="multipart/form-data"> <!-- multistep form -->
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Account Setup</li>
<li>Post an Image</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Fill in Some General Details</h2>
<h3 class="fs-subtitle">As Simple As This</h3>
<input type="text" name="update" id="title" placeholder="Update Title" />
<textarea name="description" id="description" placeholder="Short Description/Add On"></textarea>
<input type="date" name="expire" id="expire" placeholder="Expire By" value="Expire By" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<h2 class="fs-title">Upload Image</h2>
<h3 class="fs-subtitle">We currently only support images.</h3>
<div class="dropzone-previews dz-message" id="dropzonePreview">
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</fieldset>
</form>
</div>
</div>
<script>
Dropzone.options.msform = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "filepostupload.php",
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
uploadMultiple: false,
parallelUploads: 5,
maxFiles: 5,
paramName: "file",
previewsContainer: '.dropzone-previews',
clickable:'#dropzonePreview', //used for specifying the previews div
//used this but now i cannot click on previews div to showup the file select dialog box
// The setting up of the dropzone
init: function() {
var myDropzone = this;
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length === 0) {
var update = $('#title').val();
var description = $('#description').val();
var expiry = $('#expire').val();
var groupid = <?php echo $groupid ?>;
var request = $.ajax({
url: "updatesnofile.php",
type: "POST",
data: { update:update, description:description, expiry:expiry, groupid:groupid},
dataType:"text",
success: function(data) {
if (data=="success") {
alert('success');
} else {
alert(data);
}
},
error: function(request, err){
alert(err);
}
});
}else {
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sending", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
alert(response);
});
this.on("error", function(files, response) {
alert("error");
});
}
}
</script>
And my php script that does the file upload is :
<?php
session_start();
require 'config.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "updatefiles/";
if (isset($_POST['update']) && isset($_POST['description']) && isset($_POST['expiry']) && isset($_POST['groupid'])){
$title= mysqli_real_escape_string($mysqli,trim($_POST['update']));
$description= mysqli_real_escape_string($mysqli,trim($_POST['description']));
$expire= mysqli_real_escape_string($mysqli,trim($_POST['expiry']));
$groupid= mysqli_real_escape_string($mysqli,trim($_POST['groupid']));
$fileupload = basename($_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
$fileupload = mysqli_real_escape_string($mysqli,basename($_FILES['file']['name']));
$fileType = mysqli_real_escape_string($mysqli,$_FILES['file']['type']);
$fileSize = mysqli_real_escape_string($mysqli,$_FILES['file']['size']);
mysqli_query($mysqli,"START TRANSACTION;");
$ins = mysqli_query($mysqli,"INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','".$description."', '".$title."','{$_SESSION['userid']}', '".$expire."','".$groupid."' )");
if (!$ins) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with first insert";
return FALSE;
}
$upd = mysqli_query($mysqli,"SET #post_id_in_posts = LAST_INSERT_ID()");
if (!$upd) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with setting postid";
return FALSE;
}
$del = mysqli_query($mysqli, "INSERT INTO files (post_id,f_name, f_type, f_size) VALUES (#post_id_in_posts,'".$fileupload."', '".$fileType."', '".$fileSize."')");
if (!$del) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo "Error with Second Insert!";
return FALSE;
}
// All succeeded
mysqli_query($mysqli,"COMMIT");
echo"success";
return TRUE;
}else {
echo"formwasnotsubmitted";
}
?>
However, it keeps telling me that the form was not submitted (which means the posting of the form by drop zone fails, and therefore the data isn't posted over when there are files, the ajax works though when there are NO files), can anyone find out why? thanks!
I have managed to find the mistake, it is something to do with the way Dropzone sends the form data!
Related
I'm trying to duplicate a file and put some information in. First I used the form-method-action (Method 1). This worked. But I wanted to used Ajax to stay on the same page. So then I created Method 2 but this method doesn't work.
This is how my folder looks like. The 'Document.docx' has '$naam' in it's file
HTML METHOD 1:
<form method="post" action="kopie.php">
<ul>
<li><input type="text" name="factuur" id="factuur" placeholder="factuurnaam"></li>
<li><input type="text" name="naam" id="naam" placeholder="naam"></li>
<li><input type="submit" name="submit" id="submit"></li>
</ul>
<h2 class="ans"></h2>
</form>
HTML METHOD 2:
<ul>
<li><input type="text" name="factuur" id="factuur" placeholder="factuurnaam"></li>
<li><input type="text" name="naam" id="naam" placeholder="naam"></li>
<li><input type="submit" name="submit" id="submit"></li>
</ul>
<h2 class="ans"></h2>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function() {
$.ajax({
url: 'kopie.php',
method: 'POST',
data: {
factuur: factuur,
naam: naam
}
success: function() {
$('#ans').html("It worked");
}
})
})
})
</script>
PHP FOR BOTH METHODS:
$factuur = $_POST['factuur'];
$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
$newFile = $factuur . ".docx";
copy("Document.docx", $newFile);
$naam2 = $_POST['naam'];
if ($zip->open($newFile) === TRUE) {
$oldContents = $zip->getFromName($fileToModify);
$newContents = str_replace('$naam', $naam2, $oldContents);
$zip->deleteName($fileToModify);
$zip->addFromString($fileToModify, $newContents);
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
$newFilePath = 'factuur/' . $newFile;
//Move the file using PHP's rename function.
$fileMoved = rename($newFile, $newFilePath);
You need to define your input value on your data.
$(document).ready(function(){
$("#submit").click(function() {
$.ajax({
url: 'kopie.php',
method: 'POST',
data: {
factuur: $('input[name=factuur]').val(),
naam: $('input[name=naam]').val()
},
success: function() {
$('#ans').html("It worked");
}
})
})
})
Try this in your AJAX - I'll note the changes.
$(document).ready(function(e){
e.preventDefault(); //keeps the page from refreshing
$("#submit").click(function() {
//notice I'm gathering the form data here.
var data = { 'factuur' : $("#factur").val(),
'naam' : $("#naam").val()
}
$.ajax({
url: 'kopie.php',
method: 'POST',
data: data, //referencing the data variable above
dataType: html
success: function() {
$('#ans').html("It worked");
}
})
})
})
I have seen this tutorial and tried Form submit with ajax without refresh
It was working fine when i had the php code in my index.php. But now when i added the js and copied the php code in reply.php . it's not working.
I am not even sure does the php works in same way with ajax or not .
someone please help me to submit this form in database .
index.php
begin snippet: js hide: false console: true babel: false -->
<div id="comment-box">
<div class="form-group">
<form method="post" id="reply" enctype="multipart/form-data" style="width: 85%;" >
<div class="input-group">
<input type="file" name="image2" class="file" id="imgInp"/>
<span class="input-group-btn">
<button class="browse btn btn-primary input-md" type="button" ><i class="glyphicon glyphicon-picture"></i>I</button>
</span>
<input type="text" placeholder="say something" class="form-control" name="comment"/><br/>
<span class="input-group-btn">
<button class="btn btn-info" >submit</button>
</span>
</div>
<div>
<img id="blah" src="/final/images/blank.jpg" style=" width:7%; float:left; " />
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reply').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'reply.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#fcomment-box').fadeOut('slow', function(){
$('#comment-box').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
</div>
and here is php reply.php:
[note: this was working fine when it was in the same index.php. i just copied the whole php code in reply.php]
<?php
// these php variables are from index.php . will this work now like these are included ??
$user =$_SESSION['user_email'];
$get_user = "select * from users where user_email='$user' ";
$run_user = mysqli_query($con,$get_user);
$row = mysqli_fetch_array($run_user);
$user_id2 = $row['id'];
$user_name2 = $row['user_name'];
if( $_POST ){
global $con;
global $user_id2;
$comment = $_POST['comment'];
$post_image2 = $_FILES['image2']['name'];
$image_tmp2 = $_FILES['image2']['tmp_name'];
$fileType = $_FILES["image2"]["type"];
$fileSize = $_FILES["image2"]["size"];
$fileErrorMsg = $_FILES["image2"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $post_image2); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$post_image2 = preg_replace('#[^a-z.0-9]#i', '', $post_image2);
$post_image2 = time().rand().".".$fileExt;
date_default_timezone_set("America/New_York");
$date = date('Y-m-d H:i:s');
if ( $_FILES['image2']['name']=='') {
$insert =" insert into comments (post_id,user_id,comment,author_name,date) values('$post_slug','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
else if($fileSize > 1048576) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 1 Megabytes in size.";
// Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
}
else if (preg_match("/.(gif)$/i", $post_image2) ) {
// This condition is only if you wish to allow uploading of specific file types
$post_image2 = 'resized_'.$post_image2 ;
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
else{
if (!preg_match("/.(gif|jpg|png)$/i", $post_image2) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
// Remove the uploaded file from the PHP temp folder
}
else{
move_uploaded_file($image_tmp2,"images/$post_image2");
// ---------- Include Universal Image Resizing Function --------
include_once("2ak_php_img_lib_1.0.php");
$target_file = "images/$post_image2";
$resized_file = "images/resized_$post_image2";
$wmax = 260;
$hmax = 380;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function -----------
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
}
}
?>
$(document).on("submit", "#reply", function(e){
e.preventDefault();
var fd = new FormData();
var file = $("#imgInp")[0];
fd.append("image2", file.files[0]);
fd.append("comment", $(this).find('input[name="comment"]').val());
$.ajax({
url: 'reply.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
}).done(function (data){
$('#fcomment-box').fadeOut('slow', function(){
$('#comment-box').fadeIn('slow').html(data);
});
}).fail(function(){
alert('Ajax Submit Failed ...');
});
});
I have a textarea element,dropdownlist element and a dropzone area in a div.The images,video,pdf files are successfully uploading into uploads folder(no issues).The text area and dropdown values are also successfully getting inserted into database via jquery and ajax file,when submit button is clicked(submit button works on jquery).My requirement is ,how to send dropzone file values through Jquery AJAX(through same jquery AJAX where the text area and drop-down values are sent) on that submit button click event...
The html code :
<div class="panel">
<textarea placeholder="Hi!" class="form-control input-lg p-text-area" name="update" id="update" ></textarea>
<div class="panel-footer">
<ul class="nav nav-pills">
<li><select name="selectcategory" id="selectcategory" required>
<option value="">----select category-----</option>
<option value="option1">1</option>
<option value="option2">2</option>
<option value="option3">3</option>
<option value="option4">4</option>
</select></li>
<input type="submit" value="Update" name="update" id="u" class="btn btn-info pull-right update_button">
<li> <form action="upload_file.php" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
<i class=" fa fa-camera"></i>
</li>
</ul>
</div>
</div>
The jquery code:
/* Update Button Click */
$(".update_button").click(function()
{
var updateval = $("#update").val();
var cate=$("#selectcategory").val();
var dataString = 'update='+updateval+'&Category='+cate;
if($.trim(updateval).length==0 && $.trim(cate).length==0)
{
alert('ENTER SOME TEXT!!');
}
else
{
$.ajax({
type: "POST",
url: $.base_url+"message_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#update").val('').focus();
$("#selectcategory").val('');
//var c=$('#update_count').html();
//$('#update_count').html(parseInt(c)+1);
$(".dropzone").hide();
}
});
}
return false;
});
upload_file.php
<?php
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = 'uploads'; //2
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $_FILES['file']['name']; //5
move_uploaded_file($tempFile,$targetFile); //6
}
?>
The dropzone file i use:
dropzone-amd-module.js
Use params. http://www.dropzonejs.com/#params
Dropzone.options.dropzoneBox = {
url: 'url here',
params: {
new_value: 'value'
},
init: function(){
this.on('success', function (data, xhr) {
console.log(data, xhr);
});
};
If someone need!
I also needed to pass extra value from select box and this solution worked for me (i do not use form here):
Dropzone.options.myDropzone = {
url: "upload.php",
autoProcessQueue: true,
width: 300,
height: 300,
maxFilesize: 30,
progressBarWidth: '100%',
init: function () {
this.on("sending",function(file,xhr,data){
data.append("fileCategory",$('#fileCategory').val());
});
this.on("complete", function (file) {
//some action here
});
}
};
fileCategory work as $_POST
i am trying to upload file using ajax.
form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php">
<div class="feedback-form-inputs col-5">
<div class="input-field">
<select id="type" required>
<option value="quiz">Quiz</option>
<option value="midterm">Midterm</option>
<option value="final">Final</option>
</select>
</div>
<div class="input-field">
<input type="text" id="professor"/>
</div>
<div class="input-field">
<input type="text" id="name"/>
</div>
<div class="input-field">
<input type="file" id="uploaded_file" name="file" accept="" required />
</div>
</div><!-- END feedback-form-inputs -->
<div class="clear"></div>
<input type="submit" value="submit" onclick="submit() />
<div id="upload-status"> </div>
</form>
my function for opening ajax are in the external file.
function addPastTest1(cid){
// form variables
var type = _("type").value;
var professor = _("professor").value;
var name = _("name").value;
var fileSelect = _('uploaded_file');
var status = _('upload-status');
event.preventDefault();
// Update status text.
status.innerHTML = 'Uploading...';
// Get the selected files from the input.
var file = fileSelect.files[0];
var FileName = file.name;
var FileSize = file.size;
var allowed = ["msword", "pdf","pages"];
var found = false;
// check if the extension of the file match the allowed ones
allowed.forEach(function(extension) {
if (file.type.match('application/'+extension)) {
found = true;
}
})
if (FileSize >10204){
status.innerHtml = 'File must be less than 1mb in size';
}
if (found==true){
// Create a new FormData object.
var formData = new FormData();
// Add the file to the request.
formData.append('file', file, FileName);
// Set up the request.
var ajax = ajaxObj("POST", "ajaxResponse.php");
ajax.onreadystatechange = function(){
if (ajaxReturn(ajax)==true){
if (ajax.responseText=='failed'){
status.innerHtml = "failed to upload file";
}
else {
status.innerHtml = 'uploaded';
alert(ajax.responseText);
}
}
}
ajax.send(formData); //ajax.send("f="+formData+"&t="+type+"&p="+professor+"&n="+name+"&cid="+cid+"&fn="+FileName);
}
}
so i am sending formData to the php. but at this point i can not take the file from form data and upload it to the server.
here is my php
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
Also i want to grab inputs with the file and process them together. Upload file, and insert inputs into database.
The simplest one I can find. :)
jQuery code
$("#form-id").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "file-to-call.php",
type: "POST",
data: new FormData(this),
cache: false,
processData: false,
success: function(data) {
//handle success
}
});
}));
HTML code
<form name='form1' method='post' enctype='multipart/form-data' id='form-id'>
<input type='submit' id='input' value='Upload' />
</form>
I am trying to develop a PHP based application to upload a file to the web server
the jquery code goes like this
<form action="upload.php" method="post" enctype="multipart/form-data" name="upload">
<input name="uploaded_file" type="file"
style="border-radius:0px; width:900px; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif" required/>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="hidden" name="id" value=<?php echo $getid; ?> />
<br/>
<br/>
<input name="Upload" type="submit" value="Upload" class="btn btn-success btn-large" style="border-radius:0px;" id="uploadfile"/>
</form>
<div class="progress" id="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#progress').hide();
$('#uploadfile').click(function(){
$('#progress').show();
});
});
</script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html('Uploaded sucessfull');
}
});
})();
</script>
and the php code goes like this
<?php
include('connect.php');
include('antivirus.php');
$virusstatus='FALSE';
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$filedesc= 'Enter Description';
$fname= mt_rand(1000,9999);
$id=clean($_POST['id']);
//upload random name/number
$rd2 = mt_rand(1000,9999)."_File";
//Check that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload")) {
//Determine the path to which we want to save this file
//$newname = dirname(__FILE__).'/upload/'.$filename;
$newname="uploads/".$rd2."_".$filename;
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
$vsig=scanfile($newname);
$query=mysql_query("select * from virussig")or die(mysql_error());
while($image=mysql_fetch_array($query))
{
if($vsig==$image['vsig'])
{
$virusstatus='TRUE';
}
}
if($virusstatus=='TRUE')
{
die("This file contains some Virus signatures which is not allowed");
}
else
{
mysql_query("INSERT INTO up_files (id,fdesc,floc,fdatein,fname) VALUES ('$id','$filedesc','$newname',NOW(),'$fname')");
header("location: iconview.php?id=".$id);
}
}
}
}
?>
my problem is whenever error occurs in php during file upload,it gives file upload sucessful in jquery.
I want the solution to somhow manage the errors got in php and display in jquery
please help
Thankyou
Have something like this in your php code
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
$result = true;
return json_encode($result);
}
else
{
$result = false;
return json_encode($result);
}
Then in your ajax success call back
complete: function(xhr,data) {
if(data === true)
status.html('Uploaded sucessfull');
else
status.html('Uploaded unsuccessful');
}
Do check the syntax and json returned as well. Have written this logically.
You can also do it without json_encode. and appropriate return type in ajax call