upload image using vue js with form text fields - javascript

I started working on small project using Vue Js and I would like to add an upload file option in my contact form, I use serialize for the form because I have a lot of input text fields. but it doesn't work with append function. How can I add upload file to my serialized form
This is my code :
addProducts () {
const formData = $('#add-product').serialize()
// formData.append('image', this.selectedFile, this.selectedFile.name)
this.$axios.$post('http://endpoint.quicknsales.com/api/Product', formData).then((response) => {
this.validation(response)
if (response.success) { this.refresh = true }
})
}
A part of my HTML code :
<div class="form-group mb-2">
<div class="row">
<div class="col-md-6">
<label class="mb-0"><strong>Buying Price:</strong></label>
<input
id="product_buying_price"
v-model="formFields.product_buying_price"
type="text"
class="form-control rounded-0"
placeholder="Product Buying Price"
name="general[product_buying_price]"
>
</div>
<div class="col-md-6">
<label class="mb-0"><strong>Selling Price:</strong></label>
<input
id="product_selling_price"
v-model="formFields.product_selling_price"
type="text"
class="form-control rounded-0"
placeholder="Product Selling Price"
name="general[product_selling_price]"
>
<input id="file" type="file" name="general[file]">
</div>
</div>
</div>
How can I add the upload file to my form, as you can see I have already used append function but it doesn't work

after two days this is my solution :
const formData = new FormData()
formData.append('image', this.selectedFile, this.selectedFile.name)
$($('form-in-question').serializeArray()).each(function (i, field) {
formData.append(field.name, field.value)
})
this.$axios.$post('endpoint.com', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
this.validation(response)
if (response.success) { this.refresh = true }
})

Related

Can't send a submit fetch request

I searched for a long time without results about this question. The problem is that when I try to send an asynchronous request to another web page I don't have any response. I think the problem is where the FormData takes its values but I don't know why... Here is the code:
const addBooking_form = document.getElementById("form_addResa");
addBooking_form.addEventListener("submit", (event) => {
event.preventDefault();
// Send asynchronous request to /api/booking/new
const formData = new FormData(addBooking_form);
const searchParams = new URLSearchParams(formData);
console.log(formData);
console.log(searchParams);
const asyncReqAdd = fetch("api/booking/new", {
method: "POST",
body: formData
});
asyncReqAdd.then(response => {
return console.log(response.text() == 'undefined' ? 'Fetch reponse <=> undefined' : response);
}).then((response) => {
console.log(response)
table.innerHTML = response;
});
return console.log('New booking submited');
})
I know that the link and the form id are correct...
HTML FORM :
<form id="form_addResa">
<div class="fieldset flexCol-around">
<label for="input_lieu">Lieu *</label>
<select id="input_lieu" name="place">
<option value="none">< Séléctionner un lieu ></option>
<option value="Salammbô">Salammbô</option>
<option value="Pergola">Pergola</option>
<option value="Salon Jaune">Salon Jaune</option>
<option value="1001 Bougies">1001 bougies</option>
</select>
<div class="flexRow-around">
<div class="flexCol-around">
<label for="input_date">Date *</label>
<input id="input_date" type="date" name="date">
</div>
<div class="flexCol-around">
<label for="input_time">Heure *</label>
<input id="input_time" type="time" name="time">
</div>
</div>
<label for="input_nom">Nom *</label>
<input id="input_nom" type="text" name="name">
<label for="input_prenom">Prénom *</label>
<input id="input_prenom" type="text" name="firstName">
</div>
<div class="fieldset flexCol-around">
<label for="input_couverts">Nombre de couverts *</label>
<input id="input_couverts" type="number" name="coverts">
<label for="input_intExt">Client interne / externe *</label>
<select name="intExt" id="input_intExt">
<option value="ext">Externe</option>
<option value="int">Interne</option>
</select>
<label for="input_contacte">Contacter le client *</label>
<input id="input_contacte" type="text" placeholder="Numéro de chambre / téléphone / E-mail" name="contact">
</div>
<div class="fieldset">
<textarea id="input_note" placeholder="Note :" name="notes"></textarea>
</div>
<div class="flexRow-around">
<input type="reset" value="Annuler" style="background: white;">
<input type="submit" onclick="unselectBooking();">
</div>
</form>
Can you give me a solution for this?
You could use async/await with a try catch block to see what goes wrong.
Something like this (pseudo):
addBooking_form.addEventListener("submit", async (event) => {
event.preventDefault();
const { date, time, name, place } = Object.fromEntries(new FormData(event.target))
try {
const respone = await fetch("api/booking/new", {
method: "POST",
body: { date, time, name, place }
});
const data = await response.json()
// do something with data
console.log(data)
} catch(e) {
// do some error handling
console.log('error', e)
}
})
Update: you can use Object.formEntries on FormData to get the values of your named input fields and then pass them to the body. This way, you should have valid JSON data.
I also removed the element selector since you already got the element via event

AXIOS POST form submit to WordPress returning 200 with data returning 0

I have a contact form which I am trying to POST the data via AXIOS using formData to send email via WP_mail.
Submitting the form seems to be working in the sense of:
The page isn't refreshing/adding parameters to the url
Using for (var value of formData.values()) {console.log(value);} to check what values are being grabbed by formData, console.log shows the different input values
response.status is showing 200
The problems start with response.data returning 0 rather than the data from the form that is being submitted.
This is my form
<form class="js-process dark-form">
<fieldset>
<label for="name">First name*</label>
<input type="text" name="name" placeholder="Enter your first name" />
<label for="last-name">Last name*</label>
<input type="text" name="last-name" placeholder="Enter your last name" />
<label for="email-address">Email address*</label>
<input type="email" name="email-address" placeholder="Enter your email address" />
<label for="telephone">Telephone*</label>
<input type="tel" name="telephone" placeholder="Enter your phone number" />
</fieldset>
<fieldset>
<label for="enquiry-form">Nature of enquiry*</label>
<!-- TEMP -->
<select id="enquiry-form" name="enquiry-form" data-label-value="test">
<option disabled value="">test</option>
<option value="test">test</option>
<option value="test">test</option>
<option value="test">test</option>
</select>
<label for="your-message">Your message*</label>
<textarea name="your-message" placeholder="Please tell us your message"></textarea>
</fieldset>
<input type="submit" value="Submit">
</form>
This is my JS to POST the form data
import axios from 'axios';
const processForm = (e) => {
const form = e.target;
e.preventDefault();
// let formData = new FormData(form);
const formData = new FormData();
// Console.log all formData values for testing
for (var value of formData.values()) { console.log(value); }
formData.append('action', 'contact_form');
formData.append('first_name', 'my first name');
axios({
method: 'POST',
url: WP.ajax,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: formData,
})
.then(function (response) {
console.log(response);
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
},
(error) => {
console.log(error);
});
return false;
};
const initProcessForm = () => {
const forms = document.querySelectorAll('.js-process');
forms.forEach(form => {
form.addEventListener('submit', processForm);
});
};
export default initProcessForm;
I'm not sure what I am missing here to get the data from the form to POST correctly. I know i've not even got round to the WP_mail side of things! I am new to using AXIOS so if anyone can point me in the right direction with this code or has a better way of doing this i'd be grateful to know : )
Thanks in advance.

Fetch in forEach Javascript to send data in MongoDB

I want to use Fetch to send data in my mongoDB.
I would like to read an excel file and then submit each entry in a form.
This is my code:
<form method="post" action="/content" id="importcontent">
<label for="name" class="col-md-3 label-control">Import XLSX file:</label>
<input type="file" name="file" class="form-control" id="file">
<div style="display: none;">
<input type="text" name="title" class="form-control" id="titre">
</div>
<input type="submit">
</form>
<script src="https://unpkg.com/read-excel-file#4.x/bundle/read-excel-file.min.js"></script>
<script>
let importcontent=document.getElementById("importcontent");
let titre=document.getElementById("titre");
const input = document.getElementById('file');
importcontent.addEventListener('submit', (event)=>{
event.preventDefault();
readXlsxFile(input.files[0]).then((rows) => {
input.remove();
rows.forEach((row)=>{
titre.value=row[0];
fd= new FormData(importcontent);
fetch('/content',{
method:'POST',
body: fd
}).then(checkStatus)
.catch((error)=>{
console.error('request failed', error);
})
});
}
});
});
function checkStatus(response) {
if (response.status >=200 && response.status <300){
console.log("Ok");
}
}
It isn't working, I have an error 500.
Can you help me please?

How to escape XSS from uploaded filename?

I want to fix xss vulnerability.
Scenario - following:
1. I' ve created file with name <imgsrc=x onerror=alert(document.cookie)>
2.I have html input on my page and I try to load file created on step_1 and see:
Obviously malicious code from file name executes.
code:
<form id="uploadForm">
<div class="form-group">
<div class="custom-file">
<input class="custom-file-input" name="file" id="uploadFile" type="file" />
<label class="custom-file-label" for="uploadFile">Choose CSV file...</label>
</div>
<div class="" id="uploadSuccess">
<p class="text-success">Success!</p>
<p class="text-success" id="successText"></p>
</div>
<div class="" id="uploadError">
<p class="text-danger">Something has gone wrong!</p>
<p class="text-danger" id="errorText"></p>
</div>
</div>
</form>
js:
$("#uploadForm").off('submit').on('submit', (e) => {
let url = "rest_upload";
let form = $("#uploadForm")[0];
let data = new FormData(form);
e.preventDefault();
$.ajax({
method: "POST",
url: url,
data: data,
contentType: false,
processData: false
})
.done((data) => {
$('#uploadError').hide();
$('#uploadSuccess').show();
$('#successText').text(data);
})
.fail((err) => {
if (err.status === 401) return;
$('#uploadSuccess').hide();
$('#uploadError').show();
$('#errorText').text(err.responseText);
});
});
}
How can I prevent it?
Is it possible to prevent it on server side somehow?

AJAX does not respond to form submission

I wrote a toy program to learn AJAX, which is to submit the user registration form to web server, however, the program on the server side cannot receive the data. I guess the error is on the following JS code using jQuery:
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
},
registerResults: function() {
console.log("register success!");
} // end of registerResults
}); // end of ready
The corresponding html form is as following:
<form class="form-horizontal" role="form" id='registerForm' method='POST' action="/admin/user/signup">
<div class="form-group">
<label class="col-sm-3 control-label" for="fullname">Fullname: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="fullname" name='fullname' placeholder="Full Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="username">Username: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="username" name='username' placeholder="Username" />
</div>
</div>
<div class="form-group">
<input type='submit' value="Submit" class="register-form-button" form='user-create-form' />
</div>
</form>
can someone help me with my JS code using jQuery? Thanks a lot!
Like Felix said, your JavaScript syntax is invalid. Open up the JS console and refresh the page, and you'll see syntax errors.
Here's a shot at fixing it:
$(document).ready(function () {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData)
.done(registerResults)
.fail(registerError);
});
function registerResults() {
console.log("register success!");
}
function registerError() {
console.log("There was an error");
}
});
The registerResults function was a namespace function based on the formatting, but you only need a standard function like the below.
$(document).ready(function () {
$('#registerForm').submit(function () {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
});
function registerResults() {
console.log("register success!");
} // end of registerResults
}); // end of ready

Categories

Resources