I have been trying to upload an image to the server for a few days now. But server does not receive any image because form data object is always empty. I then tried to use a library called dropzone for image upload and it worked. But I dont want to use any library. Can somebody please help me understand why form data object is always empty when I send it? I would really appreciate it cuz it will also help me in future. Thank you.
Html Code
<form class="editProfileForm" encType="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col-12 mt-3">
<div class="text-left">
<label for="certificateImg">CertificateImage</label>
</div>
<input id="certificateImg" type="file" />
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center mt-3 mb-5">
<button class="saveBtn btn btn-primary btn-brand-lg" type="button">Save</button>
</div>
</div>
</div>
</form>
JS Code
const editProfileForm = document.querySelector('.editProfileForm');
const saveBtn = document.querySelector('.saveBtn');
saveBtn.addEventListener('click', () => {
let img = document.getElementById('certificateImg').files[0];
let formData = new FormData();
formData.append('img', img);
console.log(formData);
const doctorUpdateGeneral = async () => {
try {
const response = await axios.put(
'API here',
{
certificate: formData,
},
{
headers: {
Authorization: token,
},
}
);
console.log(response);
window.location.reload();
console.log(pmdc);
} catch (err) {
console.log(err);
}
};
doctorUpdateGeneral();
});
Change the encType attribute to enctype in the form element tag
Related
This is my mail.js file which includes this code:
const sendMail = (mail) => {
fetch("/contact",{
method: "post",
body: mail,
}).then((response) => {
return response.json();
});
};
This is my sendMail function in the index.js file which is sending contact form data to the desired email id:
transporter.sendMail(mail, (err, data) => {
if (err) {
console.log(err);
res.status(500).send("Something went wrong.");
} else {
res.status(200).send("Email successfully sent to recipient!");
}
});
And this is the HTML code of my contact form:
<div class="form">
<form id="contact-form" action="contact" method="post" role="form" class="php-email-form" enctype = "multipart/form-data">
<div class="my-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" value="submit" title="Send Message">Send Message</button></div>
</form>
</div>
Whenever I try to submit contact from data it sends it successfully and displays the message "Email successfully sent to recipient!" But with class="error-message" styling how can I fix that?
index.js
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').onsubmit = send_email;
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
}
function send_email()
{
const recipients = document.querySelector('#compose-recipients').value;
const subject = document.querySelector('#compose-subject').value;
const body = document.querySelector('#compose-body').value;
//console.log(recipients)
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body,
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
}
inbox.html
<div id="compose-view">
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
Submitting a form through Javascript via POST method but I am getting an output of GET /? HTTP/1.1" 200 1667 in terminal..
It should be 201 via POST
When I am writing the fetch function in Console.It is working fine
After submitting the form it is just returning back to the inbox page.
Since you are doing a "fetch" in your code, you should prevent the default form submission on the "submit" button click (This this the default behaviour). To achieve this you can receive the "event" as a parameter in the "send_email" function and then do a "event.preventDefault()".
function send_email(event) {
// Your code
...
// Prevent the default form submission
event.preventDefault();
}
More details # https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit
I want to send form data including a file to my express API for adding churches in my database and i want to upload church details and an image for this.
this is my HTML form :
<form action="" id="ad-bis">
<div class="form-group">
<label>INTRODU NUMEle BISERICII</label>
<input
type="text"
name="biserica"
id="biserica"
class="form-control"
/>
<span id="error_biserica" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU ORASUL</label>
<input type="text" name="oras" id="oras" class="form-control" />
<span id="error_oras" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU ADRESA</label>
<input type="text" name="adresa" id="adresa" class="form-control" />
<span id="error_adresa" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU NUME PREOT</label>
<input type="text" name="preot" id="preot" class="form-control" />
<span id="error_preot" class="text-danger"></span>
</div>
<div class="form-group">
<label for="poza">ADAUGA POZA</label>
<input type="file" id="poza" />
</div>
<div class="form-group" align="center">
<button type="submit" name="save" id="save" class="btn btn-info">
SALVARE
</button>
</div>
</form>
in my js file i created submit function:
adBis.addEventListener("submit", async e => {
e.preventDefault();
const data = new FormData();
data.append(
"data",
JSON.stringify({
nume: document.querySelector("#biserica").value,
oras: document.querySelector("#oras").value,
adresa: document.querySelector("#adresa").value,
preot: document.querySelector("#preot").value,
uid: localStorage.getItem("uid")
})
);
data.append("poza", _("#poza").files[0]);
console.log(data);
const res = await await fetch("http://localhost:8080/api/site/adaugare", {
method: "POST",
body: data
});
const serverData = await res.json();
console.log(res, serverData);
_(".info").style.display = "none";
if (!serverData.success) {
afisareEroare(data.msg);
}
console.log("ok");
await afisRezultate(localStorage.getItem("uid"));
});
then i created endpoint in express using multer tu upload file:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "../images");
},
filename: function(req, file, cb) {
cb(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
const upload = multer({
storage: storage
}).array("imgUploader", 3);
outer.post("/adaugare", (req, res) => {
console.log(req.body);
res.json({ msg: "ok" });
/*
*/
});
in my console, req.body is empty how send all data?
I tried with firebase storage but it doesn't work for me.
what I missed?
thanks!
First tip: Since you are using FormData you can pass the form in to get automatically all the values in the form.
Second, here you are awaiting twice:
const res = await await fetch("http://localhost:8080/api/site/adaugare", [...]
Lastly req.body empty is either because of lack of body-parser or, as I see here, you have not added the enctype="multipart/form-data" attribute, without this Multer won't get any data from your form.
I want to send/add notification data in database that contains image with some text data so I am not able to add this data in firebase. I tried some code for only data insertion, but it doesn't work and How do I add image in firebase?
I am adding database which is made manually for notification. I want to add further more notifications with image
database
This is my html form
<form method=post enctype="multipart/form-data">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" class="form-control" placeholder="Company" >
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Image</label>
<input type="image" class="form-control" placeholder="Image">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Redeem Steps</label>
<input type="text" id="redeem" class="form-control" placeholder="Redeem Steps">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Description</label>
<textarea rows="5" id="description" class="form-control" placeholder="Here can be your description"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" >
Image 1 <span style="color:red">*</span><!--<input type="file" id="image" name="img1" required>-->
</div>
</div>
<button type="submit" id="submitBtn" class="btn btn-info btn-fill pull-right" onclick="submitclick()">Send notification</button>
<div class="clearfix"></div>
</form>
this is js file
var title=document.getElementById("title");
var redeem=document.getElementById("redeem");
var description=document.getElementById("description");
var image=document.getElementById("image");
var submitBtn=document.getElementById("submitBtn");
var Id=1;
function submitclick(){
var firebaseref=firebase.database().ref();
var messagetitle=title.value;
var messageredeem=redeem.value;
var messagedescription=description.value;
//var messageimage=image.value;
console.log(messagetitle);
console.log(messageredeem);
console.log(messagedescription);
//console.log(messageimage);
//firebaseref.child("notification").set("vinit");
//firebaseref.child("notification").set("2");
//firebaseref.child("notification").set("messagedescription");
//firebaseref.child("notification").set("messageimage");
firebase.database().ref('notification/'+Id).set({
title : messagetitle,
redeem : messageredeem,
description : messagedescription
image : messageimage
});
console.log(Id);
Id++;
console.log(Id);
}
You cannot upload image directly into the firebase database. You have to upload the image into the firebase storage first, then you can store the image name/location/downloadUrl in the database if you want. Altough, store the download url is not the best practice.
const file = ...
const metadata = { contentType: 'image/jpeg' }; // or whatever you want
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`images/${file.name}`).put(file, metadata);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {
// If you want to show upload progress, do whatever you want with progress...
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, error => {
console.log(error);
}, () => {
// upload finished with success, you can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
});
});
If you want to store the downloadUrl into the databse then you have to store tha downloadUrl into a variable or put the database set into the upload finished callback.
The database set part should work with this way:
// The id should foloow your database structure,
// based on your posted image, should look like this:
// `noti_${id}` where the id is a number.
firebase.database().ref(`notification/${id}`).set({
...uploadData,
image: downloadUrl
});
Also, I hardly recommend you to use async await to handle promises and use cloud firestore instead of realtime database.
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....