Can't upload file in PHP using $ajax() - php

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);

Related

Upload file with AJAX jquery

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!";
}
?>

upload file and save filename failed using jquery ajax modal form

I try to upload file then save filename to mysql the method is same as upload & save file to mysql.
But my problem still happen. error message is uploadedfile is undefined.
HTML :
<form id="flowlist">
<div class="form-group">
<label for="idcar" class="control-label">ID CAR</label>
<input type="text" name="idcar" id="idcar" class="text_field form-control" required>
</div>
<div class="form-group">
<label for="upload">Upload Minute Of Meeting</label>
<input type="hidden" name="MAX_FILE_SIZE" value="20000000">
<input id="upload" name="uploadedfile" type="file">
<input type="hidden" id="filenm" name="filenm" required>
<input type="hidden" name="action" value="updateflow">
</div>
</form>
JS Script (cms.js):
dialog = $( "#flow" ).dialog({
buttons: {
"Update Data":function() {
var params=$('#flowlist').serialize();
$.ajax({
type:"post",
url:"doserver.php",
data:params,
cache :false,
async :false,
success : function() {
$('input').val("");
$('textarea').val("");
table.row('.selected').draw(false);
location.reload();
return this;
},
error : function() {
alert("Data failed to input.");
}
PHP code (doserver.php):
case 'updateflow':
/* catch variable parameter */
$idcar = mysqli_real_escape_string($dbc,$_POST['idcar']);
$file= mysqli_real_escape_string($dbc,$_POST['filenm']);
$target_path = "mom/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
/* UPDATE */
$sql ="UPDATE monitor SET Mom = '".$file."'";
$sql.=" WHERE id_car LIKE '".$idcar."'";
$res =mysqli_query($dbc,$sql) or die(_ERROR30.":".mysqli_error($dbc));
}
else { echo "There was an error uploading the file, please try again!"; }
break;
Edit
add enctype="multipart/form-data"
<form id="flowlist" enctype="multipart/form-data">
</form>
Then make some change to ajax function :
"Update Data":function() {
var formData = new FormData(this);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
data:formData,
....
});
I have no error but the idcar wasn't updated and file wasn't uploaded.
if you are using jquery better using $('#flowlist')[0] instead of this. I have solved this using :
"Update Data":function() {
if(window.FormData !== undefined)
{
var formData = new FormData($('#flowlist')[0]);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
mimeType:"multipart/form-data",
data:formData,
...
});
}
}

unable to upload file without page refresh

I need to upload a file using ajax without refreshing the page. (I tried using form element it works. but it redirects to the other page).
<!DOCTYPE html>
<html>
<head>
<title> Test File Upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file"><br><br>
<button id="submitbtn"> Upload </button>
</body>
<script>
$(document).ready(function(){
$("#submitbtn").click(function(){
var property = document.getElementById('file').files[0];
var formData = new FormData();
formData.append("file", property);
$.ajax({
url: "AjaxPhp.php",
type: "POST",
data: formData,
cache : false,
contentType : false,
processType : false,
dataType: "json",
success: function(testresponse){
if(testresponse.success == true){
alert(testresponse.messages);
} else {
alert(testresponse.messages);
}
}
})
});
});
</script>
</html>
this is my php file... please help :) thank you so much!
<?php
$con = mysqli_connect("localhost", "root", "", "learningdb") or die("connection failed");
if($_POST){
$target_dir = "testupload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
$sql = "INSERT INTO uploadfile(image) VALUES ('$target_file')";
mysqli_query($con, $sql);
$valid['success'] = true;
$valid['messages'] = "Successfully Uploaded!";
} else {
$valid['success'] = false;
$valid['messages'] = "Something went wrong...";
}
echo json_encode($valid);
}
?>
How do I proceed whith the problem. using Ajax for file upload while avoiding page reload.
To achieve this, prevent normal submission of the form.
Do this:
$("#submitbtn").click(function(e){
e. preventDefault();
If that doesn't work,
Add:
return false;
Just after the Ajax closing brace.
Apologies for the poor formatting. I'm typing via mobile
In AjaxPhp.php file , Use isset other wise ajax will not work.
if(isset($_POST)) {
//code
}
Rest all code is fine. Just add isset and it will solve the problem
#Christian jay Bringino here is how you can fix the issue.
Firstly when you are using var formData = new FormData(); it is very important to have <form> Tag because here i'm using query submit event.
Secondly it is not processType : false, it is actually processData : false,
HERE IS THE FULL ANSWERE
HTML CODE
<!DOCTYPE html>
<html>
<head>
<title> Test File Upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post" id="file_form">
<input type="file" name="file" id="file"><br><br>
<input type="submit" name="submitbtn" id="submitbtn" value="upload">
</form>
</body>
<script>
$(document).ready(function(){
$("#file_form").submit(function(e){
e.preventDefault();
var property = document.getElementById('file').files[0];
var formData = new FormData($(this)[0]);
formData.append("file", property);
$.ajax({
method: "POST",
url: "AjaxPhp.php",
data: formData,
cache : false,
contentType : false,
processData : false,
dataType:'json',
success: function(testresponse){
if(testresponse.success == true){
alert(testresponse.messages);
} else {
alert(testresponse.messages);
}
}
})
});
});
</script>
</html>
PHP code :AjaxPhp.php
Insisted of if($_POST) use if($_FILES['file']['name'])
Note: If you inserting data given by the user then use MYSQLI PREPARED STATEMENTS against sql injection here is the link click here.
Here are the 2 minor changes I made to script added by #Christian jay Bringino, and it works well .
<!DOCTYPE html>
<html>
<head>
<title> Test File Upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file"><br><br>
<button id="submitbtn"> Upload </button>
</body>
<script>
$(document).ready(function(){
$("#submitbtn").click(function(){
var property = document.getElementById('file').files[0];
var formData = new FormData();
formData.append("file", property);
$.ajax({
url: "AjaxPhp.php",
type: "POST",
data: formData,
cache : false,
contentType : false,
processData : false, //change processType to processData
dataType: "json",
success: function(testresponse){
if(testresponse.success == true){
alert(testresponse.messages);
} else {
alert(testresponse.messages);
}
}
})
});
});
</script>
</html>
AjaxPhp.php (I dont have the table with this database connection so I comment it)
<?php
//$con = mysqli_connect("localhost", "root", "", "learningdb") or die("connection failed");
if(isset($_POST)){ //use isset
$target_dir = "testupload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){
/*$sql = "INSERT INTO uploadfile(image) VALUES ('$target_file')";
mysqli_query($con, $sql);*/
$valid['success'] = true;
$valid['messages'] = "Successfully Uploaded!";
} else {
$valid['success'] = false;
$valid['messages'] = "Something went wrong...";
}
echo json_encode($valid);
}
?>

posting text file thru jQuery ajax in php and download the response file

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?

Upload and save to database with php and jquery ajax

i'm a amateur programer. I'm coding upload and insert to database function with php and jquery ajax but it not work
my form
<form>
<input type="file" id='iputfile1' />
</form>
my jquery script
iputfile1 = $("#iputfile1").val();
jQuery.ajax({
type:"POST",
url:"ex.php", //goi toi file ajax.php
data:"filename"=filename+"&+"&iputfile1="
+iputfile1,
success:function(html){
jQuery("#responseDiv").show();
jQuery("#responseDiv").html(html);
}
});
my ex.php file
$iputfile1 = $_REQUEST['iputfile1'];
print_r($iputfile1)
after select file and submit my ex.php file not recivice $_file['tmp']
<input type="file" class="file">
$(".file").on("change",function(){
var file = new FormData();
file.append('file',$('.file')[0].files[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: file,
processData: false,
contentType: false,
beforeSend:function(){
$(".result").text("Loading ...");
},
success:function(data){
$(".result").html(data);
}
});
<div class="result"></div>
in upload.php
<?php
include("database.php");
$name = $_FILES["file"]["name"];
if(move_uploaded_file($_FILES["file"]["tmp_name"], "DESTINATION/".$name)){
// insert to data base
echo '<img src="DESTINATION/'.$name.'">';
}
?>

Categories