I am using ajax to upload a file to the server and generate a url for a specific purpose. But whenever the file upload is successful, the page reloads automatically. Even the console shows "File uploaded" for a second and then reloads. Can someone help me sort this problem.
Here is the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="shortcut ico n" href="favicon.ico" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>InShare - File Sharing Made Easy</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<img src="./logo.png" alt="Inshare logo" class="logo">
<section class="upload-container">
<form action="">
<div class="drop-zone">
<div class="icon-container">
<img src="file.svg" draggable="false" class="center" alt="File Icon">
<img src="file.svg" draggable="false" class="left" alt="File Icon">
<img src="file.svg" draggable="false" class="right" alt="File Icon">
</div>
<input type="file" id="fileInput">
<div class="title">Drop your Files here or, <span id="browseBtn">browse</span></div>
</div>
</form>
<div class="progress-container">
<div class="bg-progress"></div>
<div class="inner-container">
<div class="status">Uploading...</div>
<div class="percent-container">
<span class="percentage" id="progressPercent">0</span>%
</div>
<div class="progress-bar"></div>
</div>
</div>
<div class="sharing-container">
<p class="expire">Link expires in 24 hrs</p>
<div class="input-container">
<input type="text" id="fileURL" readonly>
<img src="./copy-icon.svg" id="copyURLBtn" alt="copy to clipboard icon">
</div>
<p class="email-info">Or Send via Email</p>
<div class="email-container">
<form id="emailForm">
<div class="filed">
<label for="fromEmail">Your email</label>
<input type="email" autocomplete="email" required name="from-email" id="fromEmail">
</div>
<div class="filed">
<label for="toEmail">Receiver's email</label>
<input type="email" required autocomplete="receiver" name="to-email" id="toEmail">
</div>
<div class="send-btn-container">
<button type="submit">Send</button>
</div>
</form>
</div>
</div>
</section>
<div class="image-vector"></div>
<div class="toast">Sample message</div>
<script src="index.js"></script>
</body>
</html>
Here is the ajax section of javascript code:
const uploadFile = () => {
console.log("file added uploading");
files = fileInput.files;
const formData = new FormData();
formData.append("myfile", files[0]);
//show the uploader
progressContainer.style.display = "block";
// upload file
const xhr = new XMLHttpRequest();
xhr.open("POST", uploadURL);
xhr.send(formData);
// listen for response which will give the link
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
onFileUploadSuccess(xhr.responseText);
}
};
};
const onFileUploadSuccess = (res) => {
fileInput.value = ""; // reset the input
console.log("Uploaded");
// remove the disabled attribute from form btn & make text send
emailForm[2].removeAttribute("disabled");
emailForm[2].innerText = "Send";
progressContainer.style.display = "none"; // hide the box
const { file: url } = JSON.parse(res);
console.log(url);
sharingContainer.style.display = "block";
fileURL.value = url;
};
Even e.preventDefault() has been used to prevent page reload. But still it does. Can someone help me solve this. Thank you in advance..
Related
I am creating a Electron JS webapp with multiple pages for a project.
So far I have created a new page in a different folder for my To Do list feature.
I am running into a problem because when I enter a new task in the form It does not appear when I click submit.
Here is what is supposed to look like after I clicl Add New Task.
[![enter image description here][1]][1]
Here is what my task list looks like when I try to add a new task.
[![enter image description here][2]][2]
Here is my script.js file and html file. I appreciate any help you can give me!
SCRIPT.JS
//Uses ids that was created in html
const form = document.querySelector("#new-task-form");
const input = document.querySelector("#new-task-input");
const list_el = document.querySelector("#tasks");
form.addEventListener('submit', (e) => {
e.preventDefault();//stop the page from refreshing after submitting task
const task = input.value;
//Prevent user from submitting a empty task
if (!task) {
alert("Please enter out the task!");
}
else {
console.log("Success");
return;
}
//Getting task elements to display on page by creating DOM nodes
const task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
//Set inner value to task
task_actions_el.innerText = task;
task_content_el.appendChild(task_content_el);
task_content_el.appendChild(task_el);
})
})
HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Task List</title>
<link rel="stylesheet" href="styles.css" />
</head>
<div class="datetime">
<div class="time"></div>
<div class="date"></div>
</div>
<body>
<header>
<h1>Task List</h1>
<form id="new-task-form">
<input
type="text"
name="new-task-input"
id="new-task-input"
placeholder="What do you have planned?" />
<input
type="submit"
id="new-task-submit"
value="Add task" />
</form>
</header>
<main>
<section class="task-list">
<h2>Tasks</h2>
<div id="tasks">
<!-- <div class="task">
<div class="content">
<input
type="text"
class="text"
value="A new task"
readonly>
</div>
<div class="actions">
<button class="edit">Edit</button>
<button class="delete">Delete</button>
</div>
</div> -->
</div>
</section>
</main>
<script src="script2.js"></script>
</body>
</html>```
[1]: https://i.stack.imgur.com/aeUhW.png
[2]: https://i.stack.imgur.com/fZYrM.png
A few days ago, I started studying DOM and I tried to clone the code the Instagram for practicing. At this moment, I got this error message "Uncaught TypeError: Cannot read properties of null (reading 'vlaue')" This is my DOM(JS file)
const id = document.getElementById('text')
const password = document.getElementById('password')
document.addEventListener('keyup', function(e) {
if(!id.value && !password.value){
let color = document.querySelector('login-btn');
color.style.backgroundColor = "#FF0000";
}
});
and this is my index.html code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Westagram!
</title>
<link rel="stylesheet" href="style/login.css" type="text/css">
<link rel="stylesheet" href="style/common.css" type="text/css">
<!-- <link rel="stylesheet" href="js/login.js"> -->
</head>
<body>
<!-- 아래 모든 div들을 포함하는 제일 상위 Container -->
<div class="wrapper">
<div class="logo">
<p class="westagram">Westagram</p>
</div>
<!-- 로그인 섹션 -->
<div class="login-container">
<div class="id">
<input type="text" id="text" placeholder="Phone number, username, or email" />
</div>
<div class="pw">
<input type="password" id="password" placeholder="Password">
</div>
<div class="bt">
<button class="login-btn">Log in
</button>
</div>
</div>
<!-- 비밀번호 찾는 섹션 -->
<div class="click">
<a class="find-password">Forgot Password</a>
</div>
</div>
<script src="js/login.js"></script>
</html>
I tried const id = blabla.value
password = blabla.value
Also, I tried using "querySelctor" all of them but still have same issue. Could you help me out this error? I really appreciate it! I struggling with this whole day...
Thank you for helping me out in advance.
I've added an else block, hope you won't mind, it's meant to make the difference. If you are using querySelector you must add the . class symbol, before login-btn like that .login-btn Additionally - you do not close the body tag.
If you set JavaScript in the head tag, you need to use the script tag for that, not link tag. For example, like <script src = "script.js" defer> </script>
Now It's should works fine, Best regards !
const id = document.getElementById("text");
const password = document.getElementById("password");
document.addEventListener("keydown", function (e) {
if (!id.value && !password.value) {
let color = document.querySelector(".login-btn");
color.style.backgroundColor = "#FF0000";
} else {
let color = document.querySelector(".login-btn");
color.style.backgroundColor = "#008000";
}
});
<body>
<div class="wrapper">
<div class="logo">
<p class="westagram">Westagram</p>
</div>
<div class="login-container">
<div class="id">
<input
type="text"
id="text"
placeholder="Phone number, username, or email"
/>
</div>
<div class="pw">
<input type="password" id="password" placeholder="Password" />
</div>
<div class="bt">
<button class="login-btn">Log in</button>
</div>
</div>
<div class="click">
<a class="find-password">Forgot Password</a>
</div>
</div>
<script src="js/login.js"></script>
</body>
you should use identifiers when querySelector is in your code so:
let color = document.querySelector('.login-btn');
This is my Controller can anybody tell me what I have to add more so that I can add multiple images to my database I was instructed to use loops but I don't exactly know where to use so I have added my controller which allows me to upload single image but its no use for uploading multiple images. The second code is my blade file means my view where I created a form and the input type of my image is 'file' and name is 'filename' And I have used image intervention of Laravel so any help would be appreciated.
public function upload(){
$images = ImageModel::all();
return view('uploadimage',compact('images'));
}
public function uploadImage(Request $req){
$this->validate($req, [
'filename' => 'required',
'filename.*' => 'images|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$title = $req->title;
$slug = Str::of($title)->slug('-');
$alttext = $req->alttext;
$originalImage= $req->file('filename');
$thumbnailImage = Image::make($originalImage);
$thumbnailPath = public_path().'/thumbnail/';
$originalPath = public_path().'/images/';
$temp = $originalImage->getClientOriginalName();
$temp_ext = explode(".",$temp);
$ext = end($temp_ext);
$filename = time().".".$ext;
$thumbnailImage->save($originalPath.$filename);
$thumbnailImage->resize(150,150);
$thumbnailImage->save($thumbnailPath.$filename);
$imagemodel= new ImageModel();
$imagemodel->title=$title;
$imagemodel->slug=$slug;
$imagemodel->alttext=$alttext;
$imagemodel->filename=$filename;
if($imagemodel->save()){
return redirect()->back()->with('msg','Succesfully Uploaded');
}
}
And my blade.php file is also included.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Image Upload</title>
<style>
img {
border-radius: 2px;
padding: 3px;
width:200px;
height:100px;
}
</style>
</head>
<body>
<div class="container">
<h2>Image Upload Using Intervention</h2>
#if(Session::has('msg'))
<div class="alert alert-success">
{{ Session::get('msg')}}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{URL::to('upload-image')}}" method="post" enctype="multipart/form-data">
{{csrf_field() }}
<div class="form-group">
<label for="">Title</label>
<input type="text" class="form-control" name="title" id=" ">
</div>
<div class="form-group">
<label for="">Image</label>
<input type="file" multiple class="form-control" name="filename" id="imgInp">
<img width= " 200px"id="blah" src="#" alt="your image" />
</div>
<div class="form-group">
<label for="alttext">AltText</label>
<input type="text" class="form-control" name="alttext" id=" ">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
<hr>
<div class="container">
<div class="card">
<div class="card-header">
<h2>Uploaded Images</h2>
</div>
<div class="card-body">
#if($images)
#foreach($images as $i)
<img src="{{ asset('images/'. $i->filename)}}" alt="">
<!-- {{ $i->filename}} -->
#endforeach
#endif
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
$("#imgInp").change(function() {
readURL(this);
});
</script>
</body>
</html>
This one is without using jquery ajax
//controller
$files = $request->file('images'); //get all files
$images = [];
foreach($files as $file){
$images[] = [ 'image_name' => $this->storeImage($file,'your_path') ];
}
/*storeImage function could be in same controller or a separate trait file,
if you want to reuse image upload functionality in other controller(for image upload)*/
public function storeImage($file, $path)
{
$name = str_replace(" ", "_", $file->getClientOriginalName());
$file->storeAs($path , $name);
return $fileName;
}
ImageModel::insert($images); //save all record at once
//in html code change this line
<input type="file" multiple class="form-control" name="filename[]" id="imgInp">
And for better practice laravel has Form Request, A separate request class containing validation logic. To create one you can use below Artisan command:
php artisan make:request AnyNameRequest
This question already has an answer here:
How to upload a file via POST (doPost) to a Google Script's Web App?
(1 answer)
Closed 3 years ago.
I have an HTML form that lets the user upload a file. I want to then upload that file to my google drive.
My Javascript when the user clicks submit.
var data = new FormData();
data.append('resume', document.getElementById('file'));
fetch(scriptURL, {method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
My google script
doPost(e){
uploadFile(e.parameter['file])
}
function uploadFile(file, name){
var blob = file.myFile;
var name = "file";
var contentType = "application/pdf";
var fileBlob = Utilities.newBlob(blob, contentType, name);
var file = folder.createFile(fileBlob);
}
I want the uploaded pdf to be stored in my google drive but What my current code gives me is a 9 byte pdf file that just says undefined
Try this -
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Form').setTitle('Form')
}
function upload(obj) {
var blob = Utilities.newBlob(Utilities.base64Decode(obj.data), obj.mimeType, obj.fileName)
DriveApp.createFile(blob);
return 'Done';
}
Form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<base target="_top">
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Montserrat', sans-serif;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
function uploadData() {
const f = document.getElementById('upFile');
[...f.files].forEach((file, i) => {
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
const obj = {
fileName: f.files[i].name,
mimeType: data[0].match(/:(\w.+);/)[1],
data: data[1]
};
var buttonID = document.getElementById('uploadButton');
$(buttonID).attr("disabled", "disabled");
google.script.run.withSuccessHandler((id) => {
M.toast({
html: id
});
$(buttonID).removeAttr("disabled");
}).upload(obj);
}
fr.readAsDataURL(file);
});
}
</script>
</head>
<body>
<div class="container center">
<div id="upload" class="col s12">
<form onsubmit="event.preventDefault(); uploadData()">
<div class="row">
<div class="input-field col s12 m6 l4 offset-m3 offset-l4">
<div>
<h4><br /></h4></div>
<div class="file-field input-field">
<div class="btn blue">
<span>File</span>
<input type="file" name="upFile" id="upFile" required="" aria-required="true">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload file" required="" aria-required="true">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 m6 l4 offset-m3 offset-l4">
<button class="waves-effect btn blue" type="submit" id="uploadButton">Upload</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
I took the liberty of adding some Materialize CSS - hope that's alright :)
Hello I have this code using javascript & html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Signup Form</title>
<!-- css -->
<link rel="stylesheet" href="style.css">
<style>
.box {
max-width: 500px;
margin-left: auto;
margin-right: auto;
}
</style>
<!-- js -->
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div class="hero is-fullheight is-info is-bold">
<div class="hero-body">
<div class="container">
<h1 class="title has-text-centered">Test</h1>
<div class="box">
<!-- our signup form ===================== -->
<form id="signup-form" #submit.prevent="processForm">
<!-- name -->
<div class="field">
<label class="label">Username</label>
<input
type="text"
class="input"
name="name"
v-model="name">
</div>
<!-- email -->
<div class="field">
<label class="label">Password</label>
<input
type="password"
class="input"
name="email"
v-model="email"
#blur="validateEmail">
<p class="help is-danger" v-if="errors.email">
Please enter a valid email.
</p>
</div>
<!-- submit button -->
<div class="field has-text-right">
<button type="submit" class="button is-danger">
Log In
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
var app = new Vue({
el: '#signup-form',
data: {
name: '',
email: '',
errors: {
name: false,
email: false
}
},
methods: {
processForm: function() {
console.log({ name: this.name, email: this.email });
onclick="test.html";
},
validateEmail: function() {
const isValid = window.isValidEmail(this.email);
this.errors.email = !isValid;
}
}
});
function isValidEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>
</body>
</html>
And I would want that when I click on the button I can go to the page by the name of test.html I tried to use href = "test.html but it does not work. I think I have to write it in Javascrit but even using action = "test.html" it does not work...
Could you help me please ?
Thank you very much!
It seems like what you're trying to do is redirect to a new page. Try:
window.location = "test.html";
instead of:
onclick="test.html";
to my knowledge, all onclick="test.html" does is create a variable "onclick" with the string value "test.html". Setting window.location with the URL you would like to redirect to will navigate the user to that URL. More on window.location here: https://developer.mozilla.org/en-US/docs/Web/API/Window/location