AJAX Code For Uploading - javascript

My html page for uploading has only two things on it: a file open button, and a Submit. It's no problem getting the open dialog up, but after the user clicks OK, where can I find the path string?
</td>
<td style="width: 109.8pt; padding: .75pt .75pt .75pt .75pt" width="146">
<input id="file" name="file" type="file">
<p class="MsoNormal"> </p>
</td>
Does the php file below come with development tools, or is it part of default Windows javaScrpt?
action="upload.php"

Pekka is correct, this has nothing to do with either asp.net or javascript. When you submit a file upload (whether it be in an asp.net app or php) there will be some standard Response information, some of which will be details on the selected file (filename, etc.).
A quick Google search brings up several open source PHP upload utilities, as well as file upload DOM references, such as:
http://sourceforge.net/projects/uploadtool/
http://www.tizag.com/phpT/fileupload.php
http://www.w3schools.com/php/php_file_upload.asp
I'd recommend editing your question to exclude the asp.net tag and replace it with PHP. That way more PHP developers will see your question.

Try the below code
You have to make an "images" folder in the current directory and make two files :
1: Index.php 2: upload.php
You will also get the image name in the success which can be used for saving image name in the database.
1: Index.php
<html>
<head>
<title>
</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" >
var imgName = "";
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST" ,
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
data = JSON.parse(data);
imgName = data.path;
var pic = imgName;
},
error: function () {}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" name="pic" id="pic">
<br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
2: Upload.php
<?php
if (is_array($_FILES)) {
if (is_uploaded_file($_FILES['pic']['tmp_name'])) {
$sourcePath = $_FILES['pic']['tmp_name'];
$targetPath = "./images/" .time(). $_FILES['pic']['name'];
if (move_uploaded_file($sourcePath, $targetPath)) {
$imgPath['path']=$targetPath;
echo json_encode($imgPath);
}
}
}

Related

Javascript & PHP ajax error: "Undefined array key"

for several days I have been facing the problem that PHP cannot find my index.
What I've tried:
Change the data name in ajax
I added the code from PHP Create.php to create.php (at the beginning and at the end of the code)
Various ajax possibilities
The goal
I want to save an image which I have cropped with (cropper.js), using PHP on a SQL server.
My code:
OnSetData.js
canvas = cropper.getCroppedCanvas({
width:700,
height:700
});
canvas.toBlob((blob) => {
url_img = URL.createObjectURL(blob);
//url_img = blob:https://localhost/a37a7cd8-ad48...
$.ajax(
{
url:'assets/php/PHPCreate.php',
type: 'POST',
data: {'image':url_img},
success:function(output) {
console.log('Upload success: ' + output);
//Upload sucess: <output is empty>
},
error() {
console.log('Upload error');
},
});
}, 'image/png');
PHPCreate.php
if (isset($_POST['save_submit']))
{
$data = $_POST["image"];
//Warning: Undefined array key "image" in ..\assets\php\PHPCreate.php on line ..
echo($data);
}
create.php
<link href="assets/assets/cropperjs-main/dist/cropper.css" rel="stylesheet">
<script src="assets/assets/cropperjs-main/dist/cropper.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/OnSetData.js"></script>
<?php
include './assets/php/PHPCreate.php';
?>
.
.
.
.
<form id="formUpload" action="" method="post" class="form-inline" enctype="multipart/form-data">
<button class="btn btn-primary text-uppercase" role="button" name="save_submit" type="submit">Save</button>
</form>
i think you will open create.php in browser
create.php has a form that sends "save_submit" to izself as a new request
so create.php will be opened again but this time with "save_submit", nothing else, so yes, there is no image, that is correct
now lets look at OnSetData.js:
it makes a separate request to PHPCreate.php with "image", but no "save_submit" so PHPCreate.php will do nothing
to clearify:
the button in the form will make a site navigation
OnSetData.js will make a request on its own
both request are handled in separate

How to upload a file in Webform using javascript to have it access in global PHP variable $_FILES

I need help and almost crazy. I found a shitload of answers but they all do to work or at least work just a bit !?!
My task is to use a html form and upload one file or more to the webserver using ajax und recieving an answer after evaluation of php. Best I want to send form input information as well as file by an $ajax Request.
I do not understand the syntax.
So can the one or other person ...
a) Tell me how to do correctly one and also a list of files.
How to upload form data and files in one go.
b) What is the structure in detail of the file object
file = $('#file0')[0].files[0] <- I am totally lost, except that
|_____________| '#file0' is the id of the input
? |________| item 'file'
?
in the following piece of code below
Many thanks in advance.
Marvin
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function ajax_file_upload(){
var fd = new FormData();
var file;
// file = $('#file0')[0].files[0]
// fd.append('file0', file);
var formfiles = document.querySelectorAll('[type=file]');
// we start from since the first two input comes from a different form
for (let i = 0; i < formfiles.length; i++) {
var file = formfiles[i].files[0];
var id = 'file' . i;
fd.append( id , file );
alert( file.name );
}
$.ajax({
url: './ajaxupload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
alert(response);
},
error: function(response){
alert("Error occurred while trying to upload file");
}
});
}
</script>
</head>
<body>
<form method="post" action="JavaScript:ajax_file_upload();" enctype="multipart/form-data" id="myform">
<input type="file" id="file0" name="file0" />
<input type="file" id="file1" name="file1" />
<input type="file" id="file2" name="file2" />
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP in script ajaxupload.php:
print_r $_FILES;
I have found the right piece of code I was looking for ...
$.ajax({
...
data: new FormData($('#webform')[0]),
contentType:false,
cache:false,
processData:false,
mimeType: "multipart/form-data",
success: function( upload ){},
...
});

Reading in files from local disk in php asynchronously

I've downloaded files from my svn that are now stored in a folder on my local disk. The folder name is cs_DATA and within the folder I have another folder which contains all the files (unncessary but I just saved it that way). These files are the code files I have stored in subversion. Most of these files are php files. How can I read in documents (that aren't "txt") which are located on my local disk and open them on a website that uses php. Currently when I load them in, it echoes out as an empty string. This is what I have
index.php
<script>
$(function() {
$('#getData').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "endPoint.php",
data : { field2_name : $('#userInput2').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#displayParse").html(html);
//$('[name=field1_name]').val('');
}
});
});
});
</script>
<form id="comment_form" action="endPoint.php" method="GET">
Enter the file you would like to view:
<input type="text" class="text_cmt" name="field2_name" id="userInput2"/>
<input type="submit" name="submit" value="submit" id = "getData"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id="displayParse">
</div>
endPoint.php
<?php
$filePath = $_GET["field2_name"];
$url = "cs_DATA/files/" . $filePath;
$contents = file_get_contents($url);
echo '<div class="comment">', htmlspecialchars($contents),'</div>';
?>
Nothing is printing out so I can only assume that how I'm accessing my local files is incorrect. I've written my code on phpstorm and am running it on a localhost. The files I need to have access are all stored on my computer. Not sure if that affects it in any way.

Ajax: Upload the image to choose among many others

I am going to go crazy if I don't find a solution to this. I drag and drop many pictures to a drag area and then I want to choose anyone of them as to upload it on the server. However, with the following code I always upload the last one...
HTML code:
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">
<div id="dragarea"></div>
<input type="file" id="fileselect" name="fileselect[]" multiple="multiple"/>
</form>
JS code which is executed upon a click event on the image file I have dropped inside the dragarea:
var fd = new FormData($('#upload')[0]);
$.ajax({
method:"POST",
url:"upload.php",
dataType:"json",
data:fd,
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
}
})
and my upload.php
if (!empty($_FILES))
{
$sourcePath = $_FILES['fileselect']['tmp_name'];
echo json_encode($sourcePath);
$targetPath = $_FILES['fileselect']['name'];
move_uploaded_file($sourcePath,$targetPath) ;
}
What changes do I have to do as to send the clicking image for uploading and then get it on the server?
Thank you very much

input type file no returned value

Good day to all,
I'm trying to get the name/location/size of the file being uploaded. But It seems It won't display anything every time I looked in the console. But I followed everything here http://www.w3schools.com/php/php_file_upload.asp
index.php
<form id="formAction" method="POST" action="add_item.php" enctype="multipart/form-data" >
<input id="loc" type="file" name="file" />
<input type="submit" name="submit" value="Add" />
</form>
javascript
$("form#formAction").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "add_item.php",
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function() {
alert('Some fields are empty.');
}
});
});
add_item.php
// fetching data
echo $_FILES['file']['tmp_name'];
What seems to be lacking? Any help would be much appreciated. Thanks!
There are actually two problems there:
First, you missed enctype attribute on your form. This is required for plain form submissions (without ajax):
<form id="formAction" method="POST" action="add_item.php" enctype="multipart/form-data">
Second, jquery's native $.ajax doesn't support file uploads, but you can manage that using plugins, such as http://jquery.malsup.com/form/#file-upload.

Categories