i am working on csv file upload and i need to upload large csv files and then need to insert into database with field mapping.I am doing this using Jquery it is not showing any error just show the url into red color into firbug. I am not getting what is the problem?This is my script.
<script src="js/jquery.form.js"></script>
<script src="js/create_input.js"></script>
<script>
$(document).ready(function() {
$('#UploadForm').on('submit', function(e) {
e.preventDefault();
var value= $("#valS").val();
var host=$('#host').val();
//alert(host);
$(this).ajaxSubmit({
type: "POST",
url: host+"views/excel_file_import.php",
data: {value: value},
success: function(html){
$('#Exceloutput').html(html);
}
});
});
});
$(document).ready(function() {
$("#updatefields").click(function(){
var arrayOfValues = $(".bookDetails select").map(function (i, el) { return $(el).val(); }).get();
var fileName= $("#excelfile").val();
var csvState= $("#state_csv").val();
var host=$('#host').val();
$.ajax({
type: "POST",
url: host+"views/update_fields.php",
data:{str:arrayOfValues, fileName:fileName, csvState:csvState},
success: function(msg){
$('#fieldUpdate').html(msg);
}
});
return false;
});
});
</script>
<?php
$host=$_SERVER['HTTP_REFERER'];
$url=substr($host,0,-9);
?>
<input type="hidden" value="<?php echo $url; ?>" id="host">
<h1 class="page-title">Upload Csv File</h1>
<div class="container_12 clearfix leading">
<div class="grid_12" id="edit-form">
<form action="<?php echo $url; ?>views/excel_file_import.php" method="post" enctype="multipart/form-data" id="UploadForm" class="form has-validation">
<div class="clearfix">
<label for="form-upload" class="form-label">Upload File<em>*</em></label>
<div class="form-input">
<input type="file" size="50" class="text" id="excelfile" name="excelfile" required="required"/>
<input type="hidden" size="50" class="text" id="valS" name="valS" value="1" required="required"/>
</div>
</div>
<div class="form-action clearfix">
<button class="button class-button" type="submit" id="SubmitButton">Upload</button>
<button class="button class-button" type="submit" id="updatefields" name="updatefields">UpdateExcel</button>
</div>
</form>
<div id='fieldUpdate'>
</div>
<div id='Exceloutput'>
</div>
</div>
</div>
and this is excel_file_import.php code.
<?php
include("../common/connection.php");
if(isset($_POST))
{
$database= "test2";
$filename = 'test-'.$_FILES['excelfile']['name'];
$value= $_POST['value'];
$copy= move_uploaded_file($_FILES["excelfile"]["tmp_name"],"../files/".$filename);
if($copy)
{ echo "Upload Success";?>
<?php
}
}
?>
Have you tried increasing the file upload limit in php.ini file:
file_uploads = On
upload_max_filesize = 20M //needs to be in {x}M format
see more info here:
http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes
http://davidwalsh.name/increase-php-file-upload-limit-using-php-ini
http://wiki.lunarpages.com/Increase_php.ini_Upload_Limit
http://www.radinks.com/upload/config.php
I am doing this using jQuery. it is not showing any error. It is just showing the url into red color into firbug
Are both the files residing on same domain? html and php both? Firebug is showing that red color url because cross domain ajax request is not allowed normally
For uploading large files on server check these setting in php.ini file and if you don't have access of php.ini than you can change it htaccess file.Increase value of these file uploads according to your requirements.
max_input_time 1000
max_execution_time 1000
post_max_size 1000M
max_file_uploads 50
upload_max_filesize 1000M
Related
I have a page with a form that contains many fields and an image:
<form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data">
<input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFWNJTqNVYiP9">
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material" maxlength="30" style="width:30ch">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color" maxlength="10" style="width:20ch">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" maxlength="500">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input id="modelpic" name="image" type="file">
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show the preview of the image through javascript */
<div class="form-group">
<input id="AddBtn" class="btn btn-default" type="submit" value="Submit">
</form>
here is the javascript that shows the image preview in the form after selection:
$(document).ready(function() {
$('#modelpic').on("change", function () {
//shows image preview in DOM
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(this.files[0]); // read the local file
reader.onloadend = function(){ // show image in div
$('#imagePreview').show().html('<img id="theImage" src="' +this.result+ '" class="img-fluid" alt="Your Image" />');
}
}
})
});
What I need to do is show a preview of the post as it will appear before confirming submission.
How can I do it with jquery? My guess is I also have to modify the action part of the form code action="http://project.dev/model/useradd" in the html to something like self or something? Is it correct?
How do I get the submitted form data along the picture after hitting submit in jquery and use that to output the html to a preview div?
--- I also thinked to send the data to the server, save the image temporarily in public then load it in the preview. The problem is that if I use ajax to intercept the submission the image is not submitted. I think it's a problem of specyfing the data. My JS script code is like this:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
I think this is wrong probably in the datatype or something.
I have one webpage that has 2 different forms in it, the 1st one is for uploading pictures (and it's supposed to give the link of the freshly uploaded images), and the second one is a "regular" form that allows to add a product to the database, in which I use the links given by the 1st form. The problem is that I use bootstrap's jQuery, and the upload form uses the 1.7.2 version (no need to say, there are conflicts.)
Once I hit the "send" button, it's supposed to make a loading bar appear and show "100%", followed by the image URL, while the upload process is done in another file named 'upload.php'
The problem is, even though I used 'jQuery.noConflic();' it still continues to redirect me to upload.php where there's nothing to see, but I can't find the problem...
Here's the upload form :
<form id="myForm" action="upload.php" name="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Uploader une image</label>
<div class="col-md-3">
<input id="filebutton" name="filebutton" class="input-file" type="file">
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
<br />
<div id="alerte"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="envoyer"></label>
<div class="col-md-3">
<button type="file" value="envoyer" id="formenvoyer" name="myfile" class="btn btn-primary">Envoyer</button>
</div>
</div>
</div>
</form>
Here is the PHP file :
<?php
$output_dir = "img/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo "<p>Uploaded File :<br />http://grindhouseleather.esy.es/admin/img/".$_FILES["myfile"]["name"]."</p>";
}
}
?>
And here's the JS :
jQuery = jQuery.noConflict();
jQuery(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#alerte").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#alerte").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#alerte").html("<font color='red'> ERROR: Impossible d'uploader les fichiers</font>");
}
};
$("#myForm").ajaxForm(options);
});
What did I miss ?
Thank you in advance !
You shouldn't use jQuery for jQuery.noConflict();. Change it to:
jq = jQuery.noConflict();
The reason is:
jQuery = jQuery.noConflict();
The above code makes no difference.
I have been using this to process a form via AJAX and jQuery
$("#uploadBtn").click(function()
{
var formData = new FormData($('form')[0]); //--FormData here, problem line
$.ajax({
url: 'resources/ajax/ajax_upload_video.php',
type: 'POST',
xhr: function()
{
xhr = $.ajaxSettings.xhr();
if (xhr.upload)
{
xhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return xhr;
},
success: function(msg)
{
log(msg);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
It has been working fine. I added a second form on the page (Search on top, uploader on bottom)
I understand the $('form')[0] will grab the first form on the page, so naturally I changed my javascript to $('form')[1]. When I do a console.log on it, it is the correct form.
When I hit the upload button, but my php file says nothing was posted. For simplicity sake, my php file is this:
<?php
var_dump($_POST);
?>
I get just an empty array. I even gave the form I want an ID and called it this way $('#uploadForm').
I have 1 multi-select FILE input, a hidden field and a text input field.
What am I doing wrong with the FormData object?
One side not, I've been developing this page locally using WAMP and just moved it to our CentOS server that is online. Could this be a PHP setting that isn't the same as my local environment? I can't think of what PHP setting would have to do with POST
Upload Form
<form id="videoUploadForm" method="post" enctype="multipart/form-data" class="upload-form modal-edit-form">
<div class="modal-body">
<p>
<div align="center" id="fileSelect">
<input type="hidden" value="video" name="mediaType" id="mediaType" />
<input type="hidden" value="<?php echo $_GET['reelId']; ?>" name="reelId" id="reelId" />
<input type="file" name="videos[]" id="videos" accept="video/mp4" multiple />
</div>
<br>
</p>
<p>
<div id="dropbox">
<ul class="hide" id="filelist">
</ul>
<div align="center" id="nofiles">Select some file to begin</div>
</div><br>
</p>
<p>
<hr>
<label>Search Tags <small>[at least two tags separate by comma]</small></label>
<input type="text" class="span5" name="searchTags" id="searchTags" disabled />
</p>
<hr>
<p align="center">
<img src="resources/img/loader.gif" class="hide" id="loader" />
<button type="button" class="btn btn-info" name="uploadBtn" id="uploadBtn" disabled><i class="icon-circle-arrow-up icon-white"></i> Begin Upload</button>
<div id="successfulUpload" class="alert alert-success hide">
<b>The videos have been successfully uploaded.</b><br/>
</div>
</p>
</div>
</form>
Try accessing it this way:
var form = document.getElementById('form-id');
var formData = new FormData(form);
From this page on FormData.
This is the first time I am trying to upload a file and for some reason my $_FILES array is empty. I have checked again and again my HTML and it looks okay to me. When i try to debug the below code in eclipse the $_Files array is empty when i check it. I have checked the php_ini file it has:
file_uploads = On
upload_max_filesize = 2M
The form is in a fancybox modal window.
My HTML looks like this:
<form action="/CiREM/attachments/addAttachmentsModal.php?requestId=120" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="120"/>
<input type='hidden' id='listScreen' name='listScreen' value=""?>
<input type='hidden' name='MAX_FILE_SIZE' value='4000000' /><br/> <strong>Max File size Allowed: </strong>4 Mb <br/><strong>File Formats Allowed: </strong>gif,jpeg,jpg,png<br/><hr/> <div class="control-group">
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
</div>
<div class ="clear"></div>
<input id="addAttachmentsBtn" type="submit" class="btn btn-primary btn-large" value="Add Attachments"/>
</form>
My php is
<form action="<?php echo $_SERVER['PHP_SELF']."?requestId=".$requestId?>" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="<?php echo $requestId;?>"/>
<input type='hidden' id='listScreen' name='listScreen' value="<?php echo $listScreen;?>"?>
<?php
if ($CIREM['MAX_IMG_NUM']>0){
echo "<input type='hidden' name='MAX_FILE_SIZE' value='".$CIREM['MAX_IMG_SIZE']."' />";
echo "<br/> <strong>Max File size Allowed: </strong>".($CIREM['MAX_IMG_SIZE']/1000000)." Mb <br/><strong>File Formats Allowed: </strong>".$CIREM['IMG_TYPES']."<br/><hr/>";?>
<?php for ($i=1;$i<=$CIREM['MAX_IMG_NUM'];$i++){?>
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
<?php }?>
<?php }
else{
echo "<p class='alert alert-info'>Attachment uploading is not allowed</p>";
}
?>
Any help will be greatly appreciated.
Thanks,
Shakira
Without looking through that spaghetti code, first check whether your $_POST is also empty.
If it is, make sure that post_max_size is larger than upload_max_filesize. The two settings have to be congruent.
First of all sorry for the late reply but since sometimes people stumble upon old topics on stackoverflow, I decided to write the way it works for me.
So, to send files via ajax you have to use FormData.
I'll paste a link to a github project I have to submit forms via ajax so you can check the working example and paste here the snippet.
Link: https://github.com/pihh/auto-ajax-form
Code:
$( "form" ).on('submit',function( event ) {
if($(this).attr('ajax')){
event.preventDefault();
var marianaFormUrl = $(this).attr('action');
var marianaFormId = $(this).attr('id');
var marianaFormMethod = $(this).attr('type');
var marianaFormSucess = $(this).attr('success');
var marianaFormComplete = $(this).attr('complete');
var marianaFormBefore = $(this).attr('before');
var marianaFormInputs = $('#' + marianaFormId +' :input');
var marianaEncType = $(this).attr('enctype');
var marianaFormData = {};
// Set enctype
if(marianaEncType === undefined || marianaEncType == ''){
$(this).attr('enctype','multipart/form-data');
}
// Run Ajax Call
$.ajax({
url: marianaFormUrl,
type: marianaFormMethod,
dataType: 'JSON',
data: new FormData( this ),
processData: false,
contentType: false,
cache: false,
success:function(data){
// Run success
if(marianaFormSucess !== undefined && marianaFormSucess !== ''){
var fn = marianaFormSucess;
var func = fn +'( data )';
eval(func);
}
},
complete:function(data){
// Run complete
if(marianaFormComplete !== undefined && marianaFormComplete !== ''){
var fn = marianaFormComplete;
var func = fn +'( data )';
eval(func);
}
}
});
}
});
This is it, using formData it sends the files just fine.
I want to upload a file with ajax
here is my code
php, html:
<form action="uploadVideo.php" method="POST" enctype="multipart/form-data">
<input type="file" name="choosefilebtn" id="choosefilebtn" size="50" />
<input type="button" class="uploadbutton" value="upload" name="uploadbtn" id="uploadbtn" />
</form>
jquery:
$(function() {
$('#uploadbtn').click(function() {
var filename = $('#choosefilebtn').val();
alert(filename);
$.ajax({
type: "POST",
url: "uploadVideo.php",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function() {
alert("Data Uploaded: ");
}
});
});
});
when I use type sumbmit for upload button ( without ajax) it works, but with ajax it doesnt work, can any body help me,
Thanks
Edit:
Added uploadVideo.php code
$publish->remotehost=$ftpremotehost;
$publish->username=$ftpusername;
$publish->password=$ftppassword;
$publish->remotedir=CONSTANT_SERVERROOT.$folderName;
$publish->filename=$_FILES['choosefilebtn']['name'];
$publish->FTPLogin();
$publish->filecontent = fread( fopen($_FILES['choosefilebtn']['tmp_name'], "rb"),
$_FILES['choosefilebtn']['size']);
$publish->makedir($publish->remotedir);
$result=$publish->Publish();
You'll notice with the ajax call you are sending the filename, and not the contents of that file:
$.ajax({
//...
data: {
file: filename //just a name, no file contents!
},
//...
});
the only way that I am aware of sending file data via ajax is using a hidden iframe and submitting a form to that
i.e. have
<iframe style="display: none" id="formtarget" />
<form action="uploadVideo.php" method="POST" enctype="multipart/form-data"
target="formtarget">
<input type="file" name="choosefilebtn" id="choosefilebtn" size="50" />
<input type="button" class="uploadbutton" value="upload" name="uploadbtn" id="uploadbtn" />
</form>
markup
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="FileInput" id="FileInput" type="file" />
<input type="submit" id="submit-btn" value="Upload" />
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="progressbox">
<div id="progressbar"></div>
<div id="statustxt">0%</div>
</div>
<div id="output"></div>
jquery
$(document).ready(function () {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
});