I'm trying to upload a single file with JQUERY AJAX. I found this old thread - Jquery ajax single file upload
I followed the codes, but I kept getting the "Not Set" error on my php script.
Here's my HTML
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File:</label>
<input type="file" name="file" required />
</form>
<input type="button" id="upload" value="Upload"></input>
<div id="output"></div>
Here's my Jquery code. I
used latest uncompressed CDN - https://code.jquery.com/jquery-3.3.1.js
$( document ).ready(function() {
$('#upload').on('click', function(){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
Here's my php script (upload.php)
<?php
if(isset($_GET['file'])){
$filename = $_FILES['file']['name'];
if(isset($filename) && !empty($filename)){
echo 'File available';
}else{
echo 'please choose a file';
}
} else{
echo 'No file';
}
?>
Update: Changed my PHP code with below and it fixed the issue.
<?php
$info = pathinfo($_FILES['file']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;
$target = 'files/'.$newname;
move_uploaded_file( $_FILES['file']['tmp_name'], $target);
if (file_exists("files/{$newname}")) {
echo "Uploaded!";
}
?>
Related
I am trying to send a file and some information to a php page to upload to the server and store in the database. The form uploads the file to a documents folder and then stores the details in the database perfectly. However the other elements of the form, are not being sent.
Below is my code.
$(document).ready(function(){
$("#but_upload").click(function(){
var fdata = new FormData()
fdata.append("lead_id", $("lead_id").val());
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fdata.append('file',files[0]);
$.ajax({
url:'upload3.php',
type:'post',
data:fdata,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#show_message_document").fadeIn();
}else{
alert('File not uploaded');
}
}
});
}else{
alert("Please select a file.");
}
});
});
My form
<form method="post" action="" enctype="multipart/form-data" id="myform">
<input type="file" id="file" name="file" />
<input type="hidden" id="lead_id" name="lead_id" value="<?php echo $lead_id; ?>">
<input type="button" class="button" value="Upload" id="but_upload">
</form>
My Php
$lead_id = ($_POST['lead_id']);
You're trying to get "lead_id" without any selector, either use "#lead_id" or "[name=lead_id]".
Working code:
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fdata = new FormData();
fdata.append("lead_id", $("#lead_id").val());
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fdata.append('file',files[0]);
$.ajax({
url:'upload.php',
type:'post',
data:fdata,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#show_message_document").fadeIn();
}else{
alert('File not uploaded');
}
}
});
}else{
alert("Please select a file.");
}
});
});
</script>
Hope this helps!!
I was trying to upload file on server using php with jQuery's ajax() function. Below is the code which I was trying. Things worked fine when I wrote PHP code on same page without jQuery, so there is no doubt that file upload is working.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$("form").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append("files", $("#fileinput").prop("files"));
$.ajax({
url: "imgupload_.php",
type:"POST",
processData: false,
contentType: false,
data: fd,
success: function(result){
alert(result);
}
});
});
});
</script>
<form method="POST" action="#" enctype="multipart/form-data">
<input type='file' name='files' id="fileinput"/>
<input type='submit' value='Submit' name='submit'/>
</form>
imgupload_.php
if(isset($_POST["submit"])) {
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["files"]["name"]);
if (move_uploaded_file($_FILES["files"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["files"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
If you want any other info please comment below.
You're checking if(isset($_POST["submit"])) but this is not set.
Instead of just this:
var fd = new FormData();
Use this to pull in any non-file input values (such as your submit button.)
var fd = new FormData(this);
I am working on a project where the requirement is to upload a PDF file to the server in file format, e.g. /home/xyz/proect_dir/upload/file_name.pdf, and store the file path to MySQL Database. I am uploading a PDF file using PHP & AJAX. I am getting a following error.
Notice: Undefined index: uploaded_pdf
Here is my code:
upload.html
<form action="#" method="post" id="frm_upload_pdf" enctype="multipart/form-data">
<input type="file" name="uploaded_pdf" id="uploaded_pdf" accept="application/pdf" class="upload" />
<button type="submit" id="btnUploadPaper">Save</button>
</form>
upload.js
$('#frm_upload_pdf').validate({
rules: {
uploaded_pdf: { required: true }
},
messages: {
uploaded_pdf: { required: "Select pdf file" }
},
errorPlacement: function(error, element) {
error.insertAfter(element);
},
submitHandler: function() {
uploadPDF();
}
});
function uploadPDF() {
$.ajax({
url: 'upload_processor.php',
type: 'POST',
data: $('#frm_upload_pdf').serialize(),
success: function (data) {
alert(data);
}
});
}
upload_processor.php
public function uploadPaper() {
$fileName = $_FILES['uploaded_pdf']['name'];
$temp_name = $_FILES['uploaded_pdf']['tmp_name'];
if (isset($fileName)) {
if (!empty($fileName)) {
$fileType = pathinfo(FILE_UPLOAD_ROOT.$fileName, PATHINFO_EXTENSION);
$allowTypes = array('pdf');
if (in_array($fileType, $allowTypes, true)) {
//upload file to server
return move_uploaded_file($temp_name, FILE_UPLOAD_ROOT.$fileName) ? true : false;
}
return false;
}
return false;
}
return false;
}
While debugging I found that ajax does not post the file data as $_FILES, hence it is giving above error of undefined index. Any idea why it is not posting the file data as $_FILES or am I missing anything here.
I have Re-written your ajax and php codes as follows.
First you will need to create a folder called pdf in the same directory where your php codes resides.
Run the following tested codes below and its working. Let me know that its working for you
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload_processor.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
$("#errorLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
</head>
<body>
<div>
<form id="uploadForm" action="upload_processor.php" method="post">
<div id="targetLayer"></div>
<div id="errorLayer"></div>
<div id="uploadFormLayer">
<input name="uploaded_pdf" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</div>
</body>
</html>
php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['uploaded_pdf']['tmp_name'])) {
$fileName = $_FILES['uploaded_pdf']['name'];
$sourcePath = $_FILES['uploaded_pdf']['tmp_name'];
$targetPath = "pdf/".$_FILES['uploaded_pdf']['name'];
if($fileName ==''){
echo "<div id='errorLayer'>Please select file</div>";
exit;
}
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);
$allowTypes = array('pdf');
if (!in_array($fileType, $allowTypes, true)) {
echo "<div id='errorLayer'>File type is invalid</div>";
exit;
}
if(move_uploaded_file($sourcePath,$targetPath)) {
echo "<div id='targetLayer'>File uploaded successfully</div>";
?>
<?php
}
}
}
?>
View:
<script>
$("#team_image").change(function(){
var file_data = $('#team_image').prop('files')[0];
var member_name = $("#member_name").val();
var form_data = new FormData();
form_data.append('file', file_data);
$('#imgs').html("<img src='<?php echo base_url(); ?>resource/loading.gif' />");
$.ajax({
url: '<?php echo base_url(); ?>upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
$("#imgs").html(php_script_response);
}
});
});
</script>
<input id="team_image" type="file" name="team_image" />
<input id="member_name" type="text" name="member_name" />
Controller:
public function upload()
{
if ( 0 < $_FILES['file']['error'] )
{
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else
{
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = array("jpg", "jpeg", "png");
if(!in_array($ext, $allowed))
{
echo '<p id="red">Only jpg, jpeg, and png files are allowed.</p>';
}
else
{
$data = array(
'member_name'=>$this->input->post('member_name'),
'team'=>$filename
);
$sql = $this->db->insert('team',$data);
move_uploaded_file($_FILES['file']['tmp_name'], ''.FCPATH.'image/team_image/'.$_FILES['file']['name']);
if($sql==true)
{
echo '<p style="color:green;font-weight:bold;">File uploaded Successfully</p>';
}
else
{
echo '<p id="red">Unable to proceed!</p>';
}
}
}
}
In this code I have simple two file i.e. type="file" and type="text". Now, What I actually want when I click on type=" file" image and member_name will insert into database and image should be moved into a folder. I don't know where am I doing wrong? So, How can I do this? Please help me.
Thank You
Please change AJAX code, don't need to use prop method to get files data, with FormData() method, it will send $_POST & $_FILES data on the server. Also, use form tag.
Please follow below code:-
<script>
$("#team_image").change(function(){
var form_data = new FormData();
$('#imgs').html("<img src='<?php echo base_url(); ?>resource/loading.gif' />");
$.ajax({
url: '<?php echo base_url(); ?>upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
$("#imgs").html(php_script_response);
}
});
});
</script>
<form method="post" enctype="multipart/form-data">
<input id="team_image" type="file" name="team_image" />
<input id="member_name" type="text" name="member_name" />
</form>
On server side (on PHP script) you can get data by using $_FILES (Array) & $_POST (Array).
Please use this.
Requirement:
I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php
processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.
I have seen many posts but nothing is helping me out.
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
I have tried hundreds of solutions given on the net but none is working.
Here I am providing complete working example:
HTML File:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
Download
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
PHP File:
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$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 $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
Try to upload any file.
Is this useful for you?