how to send input text value - javascript

My problem is I don't know how to send inputs text values with code below.
I find this code in some website but I don't know how to send inputs text values with it because it send just files.
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
var name = _("name").value;
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("name", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<input type="text" name="name" placeholder="title" id="name"/>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
And this php code :
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
$name = $_POST['name'];
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "$fileName")){
echo "$fileName upload is complete $name";
} else {
echo "move_uploaded_file function failed";
}
?>
Please help me by editing my code and thank you.

You Just need to change code
EDIT JS FROM
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("name", file); // IMPORTANT : FROM THIS
EDIT JS TO
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("name", name); // IMPORTANT : TO THIS
FRONT END CODE
<head>
<script>
/* Script written by Adam Khoury # DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
var name = _("name").value;
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
/////////////////////////////////////////////////////////////////////
formdata.append("name", name); ////// formdata.append("name", file);
/////////////////////////////////////////////////////////////////////
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<input type="text" name="name" placeholder="title" id="name"/>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
PHP CODE
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
$name = $_POST['name'];
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, $fileName)){
echo $fileName . 'upload is complete ' . $name;
} else {
echo "move_uploaded_file function failed";
}

Run a separate function in your completeHandler() that uploads the text data via ajax after your image has uploaded.

Related

ajax uploader (with nginx)

I have a multiple file upload(images) script, with ajax XMLHttpRequest. I'm testing on mobile browsers, because they will be used. The problem is, that chrome stops when uploading 10-12 images with error:
A php on line 1 $_FILES["file1"].. not defined...
but on chrome I can upload 5 images. Mozilla doesn't have that much(max: 1). On PC the situation is completely different. The chrome uploads much more without error.
I'm running the code on my nginx web server at home. Can this be caused by the lack of certain configuration settings?
What can cause such an error?
I don't understand these operations.
Please, help me!
HTML CODE
<form method="post" id="upload_form" enctypee="multipart/form-data">
<input type="file" name="file1[]" id="file1" multiple><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var len = document.getElementById("file1").files.length;
console.log(len);
var formdata = new FormData();
for (var i = 0; i < len; i++) {
formdata.append("file1[]", document.getElementById('file1').files[i]);
}
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event) {
_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event) {
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
_("status").innerHTML = "Upload Aborted";
}
PHP
$lengthFile = count($_FILES["file1"]["name"]);
for($i=0; $i<$lengthFile; $i++)
{
$fileName = $_FILES["file1"]["name"][$i];
$fileTmpLoc = $_FILES["file1"]["tmp_name"][$i];
$fileType = $_FILES["file1"]["type"][$i];
$fileSize = $_FILES["file1"]["size"][$i];
$fileErrorMsg = $_FILES["file1"]["error"][$i];
echo $fileName ."<br>";
if (!$fileTmpLoc) {
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
}
Try to fix typo in your form tag - "enctype" instead of "enctypee"

php: customizing file upload

Following a tutorial i get a basic php file upload form, i'm newbie of php, May i ask how to get five file upload forms to send five files at the same time, each one with its own progress bar, but with a single button to start uploading all, also how to rename to a specific name the output files and to get only a specified MIME type possible to be uploaded.
Im unable to use this code in amodular way, to economize the code, without copy and paste all things.
Thanks a lot
HTML
<!DOCTYPE html>
<html>
<head>
<script>
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>UPGRADE ADAPTIVE-SETS</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</body>
</html>
PHP
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "incoming/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
<?php
if(isset($_FILES['file']))
{
$error = $_FILES['file']['error'];
if($error != 0)
{
echo 'Upload error.';
}
else
{
$size = $_FILES['file']['size'];
if($size > (1024*1024*3))
{
echo 'file < 3MB ';
}
else
{
$tip = $_FILES['file']['type'];
$name = $_FILES['file']['name'];
$extension = explode('.', $name);
$extension = $extension[count($extension)-1];
if($extension == 'jpg' || $extension == 'png' || $extension == 'gif')
{
if(!file_exists('files'))
mkdir('files');
$file = $_FILES['file']['tmp_name'];
copy($file, 'files/' . $_FILES['file']['name']);
echo 'Uploaded ';
}
else
{
echo 'Just =>JPG,PNG.';
}
}
}
}?>
Hi, For example, the example in this code

Laravel 5.2 ajax upload progress bar and TokenMismatchException in VerifyCsrfToken.php line 67

I'm trying to integrate progress bar on image upload. My code works fine when I submit form with PHP, but when I include javascript with progress bar I get error "TokenMismatchException in VerifyCsrfToken.php line 67". This is my form:
{!! Form::open(array('files' => true, 'class' => 'form', 'route' => ['backend.posts.uploadimage', $post->id])) !!}
<div class="form-group">
{!! Form::file('image', ['id' => 'image']) !!}
</div>
<hr>
<input type="button" value="Upload Image" class="btn btn-info btn-sm" onclick="uploadImage()">
{!! Form::close() !!}
This form generate hidden input field with token:
<input name="_token" type="hidden" value="jGQWC2GljiSeZrL8wvfMaH490xHOh727345U6HzK">
My javascript code is this:
function uploadImage()
{
var file = document.getElementById("image").files[0];
var id = {{ $post->id }};
var formdata = new FormData();
formdata.append("image", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("post", "{{ route('backend.posts.uploadimage', $post->id) }}");
ajax.send(formdata);
}
function progressHandler(event)
{
var percent = (event.loaded / event.total) * 100;
document.getElementById("progressPercent").style.width = Math.round(percent);
}
function completeHandler(event)
{
document.getElementById("status").innerHTML = event.target.responseText;
document.getElementById("progressPercent").style.width = 0;
}
function errorHandler(event)
{
document.getElementById("status").innerHTML = "Upload Failed";
}
function abortHandler(event)
{
document.getElementById("status").innerHTML = "Upload Aborted";
}
And method in my PostController for uploading image is this:
public function uploadImage(Requests\UploadImageRequest $request, $id)
{
$post = $this->posts->findOrFail($id);
$image = $request->file('image');
$imageName = $image->getPathName();
$newImageName = $post->id . '-' . md5(microtime());
$imageExtension = $image->getClientOriginalExtension();
$imageFile = $newImageName . '.' . $imageExtension;
$path = public_path();
move_uploaded_file($imageName, $path . '/images/img_upload/' . $imageFile);
$post->where('id', $id)->update(['image_name' => $newImageName, 'ext' => $imageExtension]);
return view('backend.posts.uploadimage');
}
How I can post token from hidden fields using pure javascript, or is there any other solution to solve this problem? Please help.
Use getElementsByName() to get the value of input field.
var _token = document.getElementsByName('_token')[0].value;
//and append the value to form data
formdata.append("_token", _token);

Combine $_FILES and $_POST into one AJAX call with Javascript only

I am having difficulty sending an ajax call that contains both a file and a string. I have no difficulty making either post or file, but not both together. I need this in pure Javascript, which i am more proficient than Jquery.
here is the code i am working with...
function uploadFile(){
var title = _('title').value;
var genere = _('genere').value;
var stars = _('stars').value;
var description = _('description').value;
var file = _("video").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("video", file);
formdata.append("title", title);
formdata.append("genere", genere);
formdata.append("stars", stars);
formdata.append("description", description);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "video_php/video_upload.php");
ajax.send(formdata);
}
function progressHandler(event){
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
This is the php.....
<?PHP
$fileName = '';
$fileTmpLoc = '';
$fileType = '';
$fileSize = '';
$title = '';
$genere = '';
$stars = '';
$description = '';
$retn= '';
if (!isset($_FILES["video"]["name"])) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}else{
$fileName = $_FILES["video"]["name"]; // The file name
$fileTmpLoc = $_FILES["video"]["tmp_name"]; // File in the PHP tmp folder
$fileType = explode('.',$fileName); // The type of file it is
$fileType = end($fileType); // The end type of file it is
$fileSize = $_FILES["video"]["size"]; // File size in bytes
$title = preg_replace('#[^a-z0-9, ]#i', '', $_POST['title']);
$genere = preg_replace('#[^a-z0-9, ]#i', '', $_POST['genere']);
$stars = preg_replace('#[^a-z0-9, ]#i', '', $_POST['stars']);
$description = preg_replace('#[^a-z0-9, ]#i', '', $_POST['description']);
}
echo $fileName.'<br/>';
echo $fileTmpLoc.'<br/>';
echo $fileType.'<br/>';
echo $fileSize.'<br/>';
echo $title.'<br/>';
echo $genere.'<br/>';
echo $description.'<br/>';
?>
I have been stuck on this for weeks. I have been through SO as well as many other sites with google. Every answer CLOSE to my desired result has been in Jquery. One solution i had was to make a 2-step form, uploading first one dataset, then the other, but i think both can be sent together for user usability. I have seen it done on several other websites.
NOTE*
Above code has been corrected. Added
formdata.append("video", file);
formdata.append("title", title);
formdata.append("genere", genere);
formdata.append("stars", stars);
formdata.append("description", description);
It is now fully functional, thanks to #Ohgodwhy
Origional Question is at Send $_POST and $_FILE data to php with JAVASCRIPT
Looks like you want the value of _('title') to be added to the formdata.
Given that you have this:
formdata.append("video", file);
All you need to do is this:
formdata.append('title', title);
The FormData object will handle the transmission of the file, and title will be available as $_POST['title'];

Single file to Multiple files upload using PHP, MySQL, JS and AJAX

I have a script to upload single file to server, pass the value of destination and save every data in the database. I would like to change that script from single file to upload multiple files.
Script:
upload.php
<!DOCTYPE html>
<?
if ($_SESSION['id'])
{
$usr = $_SESSION['usr'];
?>
<html>
<head>
<script>
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var dest = _("cat").value;
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "page/upload_verify.php?send=" + dest + "&usr=<? echo $usr ?>");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bites of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% has been uploaded... Wait...";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "File upload has been failed...";
}
function abortHandler(event){
_("status").innerHTML = "File upload has been cancelled...";
}
</script>
</head>
<body>
<h2>Upload</h2>
<form id="upload_form" enctype="multipart/form-data">
<input type="file" name="file1" id="file1" value="Choose file"><br>
<select id="cat" name="cat">
<option value="movies">Movies</option>
<option value="music">Music</option>
<option value="apps">Apps</option>
<option value="other" selected="selected">Other</option>
<option value="games">Games</option>
</select>
<br>
<input type="button" value="Upload" onclick="uploadFile(); return false;">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
</body>
</html>
<?
}
else
{
echo "<h2>You have no permission to view this file. Leave now!</h2>";
}
?>
and upload_verify.php
<?php
include ("../connect.php");
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
$usr = $_GET['usr'];
$dest = $_GET['send'];
$path = "download/$dest";
if($fileSize > 1073741824){
die('File uploaded exceeds maximum upload size.');
}
else
{
if(file_exists('test_uploads/' . $fileName)){
die('File with the same name already exist.');
}
else{
if ($fileSize > 1024 && $fileSize <= 1048576)
{
$new_FileSize = $fileSize / 1024;
$new_FileSize = round($new_FileSize, 2);
$bytes = "KB";
}
else if ($fileSize > 1048576)
{
$new_FileSize = $fileSize / 1024 / 1024;
$new_FileSize = round($new_FileSize, 2);
$bytes = "MB";
}
else
{
$bytes = "Bytes";
}
if(move_uploaded_file($fileTmpLoc, "../test_uploads/$fileName")){
echo "File $fileName has been uploaded by $usr in: $dest";
mysql_query("INSERT INTO `files` (filename, size, bytes, type, date, bywho, cat, path) VALUES (
'".$fileName."',
'".$new_FileSize."',
'".$bytes."',
'".$fileType."',
now(),
'".$usr."',
'".$dest."',
'".$path."'
)") or die("Something went wrong...");
} else {
echo "move_uploaded_file function failed";
}
}
}
?>
What I'm trying to do is to change that script so I can upload multiple files.
I've changed
<input type="file" name="file1" id="file1" value="Choose file"><br>
for
<input multiple type="file" name="file1[]" id="file1" value="Choose file"><br>
so I can select multiple files and place them in array. Next I've change some part of upload_verify.php file so I can do the same action for every file in array.
Now it looks like this:
<?php
include ("../connect.php");
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
$usr = $_GET['usr'];
$dest = $_GET['send'];
for($i=0; $i<count($_FILES['file1']['name']); $i++){
$target_path = "../test_uploads/";
$ext = explode('.', basename( $_FILES['file1']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file1']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
?>
I know that script is not finished yet, but I'm trying to do it partially so I know where I've made a mistake. Now I have no idea what went wrong. Can I count for your help, please?
Thank you very much in advance for every help I can get.

Categories