How to add image into axios data - javascript

I would like to add an image into Axios data and send the data to .Net Controller. I have never done this before with an image and I need help.
The image source it's not coming from input, but from img tag.
Any idea how to insert the image into a JSON object(data)?
Thank you in advance!
function PostOffer(){
let localhost = "https://localhost:7009";
let url = localhost + "/Client/New";
let formClientName = document.getElementById("offer-client-name").value;
let formClientEmail = document.getElementById("offer-client-email").value;
let formClientPhone = document.getElementById("offer-client-phone").value;
let formClientDate = document.getElementById("offer-client-date").value;
let formClientTotal = document.getElementById("main-calculator-total-amount-final").innerText;
if(parseFloat(formClientTotal) > 0){
if(formClientName.trim() != "" && formClientEmail.trim() != "" && formClientPhone.trim() != "" && formClientDate.trim() != ""){
let data = {
clientName : formClientName,
clientEmail : formClientEmail,
clientOfferDate : formClientDate,
clientPhone : formClientPhone,
clientTotal : formClientTotal,
};
axios.post(url, data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
ClearOfferSend();
}else{
document.getElementById("validation-inputs-send-offer").style.display = "flex";
}
}else{
document.getElementById("validation-inputs-send-offer").style.display = "flex";
document.getElementById("validation-inputs-send-offer").innerText = "Total amount can not be 0";
}
}
<div class="final-form">
<input type="text" asp-for="Name" id="offer-client-name" placeholder="name" required/>
<input type="email" asp-for="Email" id="offer-client-email" placeholder="email" required/>
<input type="text" asp-for="Phone" id="offer-client-phone" placeholder="phone" required/>
<label for="DateOffer">When do you want to start the project?</label>
<input type="date" asp-for="DateOffer" id="offer-client-date" placeholder="date" required/>
<div class="row">
<button class="btn-close-final-offer" onclick="CloseOfferForm();">Close</button>
<button class="btn-send-final-offer" onclick="PostOffer();">Send</button>
</div>
<span id="validation-inputs-send-offer">Inputs can not be empty!</span>
</div>
.NET controller:
[HttpPost]
public IActionResult New([FromBody] ClientAxiosModel offersend)
{
if (ModelState.IsValid)
{
_clientService.Create(offersend.clientName, offersend.clientEmail, offersend.clientPhone, offersend.clientOfferDate, offersend.clientTotal);
return Ok();
}
else
{
return NotFound();
}
}

If you use input type="file" you can insert image into axios with the following code:
<!-- HTML code -->
<input type="file" id="uploadImage" name="image">
// JS code
let formDataImage = document.getElementById("uploadImage").files[0];
// Add in data object too
data.image = formDataImage;

Related

How to remove unwanted element

I'm trying to write easy validation code and I have trouble. I've created element div '._error-alert' and I cant remove it if the input isn't empty.
When I press submit appears my element '._error-alert' but it doesnt disapear when I try to type something there. I'll be very grateful if u help or at least show me the other path to solve it
const form = document.querySelector('.validation__form'),
reqItems = document.querySelectorAll('._req'),
emailTest = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+[^<>()\.,;:\s#\"]{2,})$/,
onlyTextTest = /^[a-zA-Z0-9#]+$/,
onlyNums = /^[0-9]+$/;
const inputTest = (example, input) => example.test(input.value);
const formAddError = (input) => {
if (input.classList.contains('_req')) {
const createBlock = document.createElement('div');
createBlock.classList.add('_error-alert');
input.parentElement.insertAdjacentElement("beforeend", createBlock);
createBlock.innerText = `Invalid ${input.getAttribute("name")}!`;
}
input.parentElement.classList.add('_error');
input.classList.add('_error');
};
const formRemoveError = (input) => {
input.parentElement.classList.remove('_error');
input.classList.remove('_error');
};
// validates form if function validateForm didn't have any errors and removes my created elements '._error-alert'
const sendValidatedForm = (e) => {
e.preventDefault();
let error = validateForm(form);
if (error === 0) {
console.log('fine');
form.reset();
document.querySelectorAll('._error-alert').forEach((errorAlert) => {
errorAlert.remove();
});
}
};
form.addEventListener('submit', sendValidatedForm);
// there I want to check input and remove '._error-alert' if input isnt wrong
const checkInput = () => {
reqItems.forEach((reqInput, index) => {
reqInput.addEventListener('input', () => {
formRemoveError(reqInput);
});
});
};
checkInput();
const validateForm = (form) => {
let error = 0;
reqItems.forEach(reqInput => {
reqInput.value.trim();
formRemoveError(reqInput);
if (reqInput.getAttribute("name") == "email") {
if (!inputTest(emailTest, reqInput)) {
formAddError(reqInput);
error++;
}
} else if (reqInput.getAttribute("name") == "phone") {
if (!inputTest(onlyNums, reqInput) && reqInput.value.length < 8) {
formAddError(reqInput);
error++;
}
} else if (reqInput.getAttribute("name") == "name") {
if (!inputTest(onlyTextTest, reqInput)) {
formAddError(reqInput);
error++;
}
}
});
console.log(error);
return error;
};
<form action="" class="validation__form">
<div class="validation__input-list">
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="name" placeholder="Name">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input" name="surname" placeholder="Surname">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="phone" placeholder="Phone">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input _req" name="email" placeholder="Email">
</div>
<div class="validation__input-item">
<input type="text" class="validation__input-input" name="password" placeholder="Password">
</div>
</div>
<button class="validation__form-btn">Submit</button>
</form>
Set the css visibility property of the element to hidden.
const error_element = document.getElementsByClassName('_error-alert')
error_element.style.visibility = 'hidden'

why javascript-ajax submitting form multiple times

I am doing single page app. If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in javascript code?
here is my html
function reply_mail(idi) {
document.querySelector('#emails-view').style.display = 'none';
document.querySelector('#compose-view').style.display = 'none';
document.querySelector('#reply-view').style.display = 'block';
fetch(`/emails/${idi}`)
.then(response => response.json())
.then(email => {
// Print email
var strp = `${email.subject}`;
var ini = 'Re: '
document.querySelector('#reply-recipients').value = `${email.sender}`;
if (strp.slice(0, 4) == 'Re: ') {
document.querySelector('#reply-subject').value = `${strp}`;
} else {
document.querySelector('#reply-subject').value = ini.concat("", strp);
}
var output = `On ${email.timestamp} ${email.sender} wrote:|
${email.body} |
`;
// ... do something else with email ...
document.querySelector('#reply-body').value = output;
// ... do something else with email ...
console.log(email);
});
document.querySelector('#reply-submit').addEventListener('click', function(event) {
event.preventDefault();
rec = document.querySelector('#reply-recipients').value;
sub = document.querySelector('#reply-subject').value;
bod = document.querySelector('#reply-body').value;
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: rec,
subject: sub,
body: bod
})
})
.then(response => response.json())
.then(result => {
// Print result
if ('error' in result) {
console.log(result);
document.querySelector('#reply-error').style.display = 'block';
document.querySelector('#reply-error-i').innerHTML = `<p>${result['error']}</p>`;
} else {
console.log(result);
document.querySelector('#reply-error').style.display = 'none';
load_mailbox('sent');
}
});
})
}
```
<div id="reply-view">
<h3>New Email</h3>
<div class="alert alert-danger" role="alert" id="reply-error">
<div id="reply-error-i">
</div>
</div>
<form id="reply-form">
<div class="form-group">
From: <input disabled class="form-control" value="soham#example.com">
</div>
<div class="form-group">
To: <input id="reply-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="reply-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="reply-body" placeholder="Body"></textarea>
<input type="submit" id="reply-submit" class="btn btn-primary" />
</form>
</div>

Serialize HTML form to JSON with pure JavaScript

I have seen this method of serializing a form to JSON and it's working fine. My question is: How can I achieve this with pure JavaScript, without using any jQuery code? I am sorry if the question is dumb, but I'm still learning so if anyone can help me, I'll be grateful.
(function ($) {
$.fn.serializeFormJSON = function () {
var objects = {};
var anArray = this.serializeArray();
$.each(anArray, function () {
if (objects[this.name]) {
if (!objects[this.name].push) {
objects[this.name] = [objects[this.name]];
}
objects[this.name].push(this.value || '');
} else {
objects[this.name] = this.value || '';
}
});
return objects;
};
})(jQuery);
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
/* Object
email: "value"
name: "value"
password: "value"
*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
P.S.
Also in jQuery is this the right way to send multiple JSON objects from user input as One String, because I am searching for a way to do that?
You can try something like this:
function formToJson(){
var formElement = document.getElementsByTagName("form")[0],
inputElements = formElement.getElementsByTagName("input"),
jsonObject = {};
for(var i = 0; i < inputElements.length; i++){
var inputElement = inputElements[i];
jsonObject[inputElement.name] = inputElement.value;
}
return JSON.stringify(jsonObject);
}
This solution works only if you have a single form on the page, to make it more general the function could e.g. take the form element as an argument.
You can use Array.reduce, something like
// get array of all fields and/or selects (except the button)
const getFields = () => Array.from(document.querySelectorAll("input, select"))
.filter(field => field.type.toLowerCase() !== "button");
// get id, name or create random id from field properties
const getKey = field => field.name
|| field.id
|| `unknown-${Math.floor(1000 * Math.random()).toString(16)}`;
// get data, simple object
const getFormData = () => getFields()
.reduce( (f2o, field) => ({...f2o, [getKey(field)]: field.value}), {} );
// log the result
const logResult = txt => document.querySelector("#result").textContent = txt;
// get data, array of field objects
const getMoreFormData = () => getFields()
.reduce( (f2o, field) =>
f2o.concat({
id: field.id || "no id",
name: field.name || "no name",
idGenerated: getKey(field),
type: field.type,
value: field.value }
),
[] );
// handling for buttons
document.addEventListener("click", evt => {
if (evt.target.nodeName.toLowerCase() === "button") {
console.clear();
logResult(/simple/.test(evt.target.textContent)
? JSON.stringify(getFormData(), null, " ")
: JSON.stringify(getMoreFormData(), null, " ")
);
}
} );
<form action="#" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" value="Pete"/>
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="pete#here.com"/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<div>
<label>Field without name or id</label>
<input type="number" value="12345" />
</div>
</form>
<p>
<button>Data simple object</button> <button>Data fields array</button>
</p>
<pre id="result"></pre>
Remember that for checkboxes, value attribute can be either on or off string. This is unwanted. Here is my solution, based on this codepen.
let json = Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.reduce((json, element) => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
return json;
}, {});
OR
let json = {};
Array.from(form.querySelectorAll('input, select, textarea'))
.filter(element => element.name)
.forEach(element => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
});
OR (with typescript)
export type FormJson = {[key: string]: boolean | string};
export const toJson = (form: HTMLFormElement): FormJson =>
Array.from(form.querySelectorAll<HTMLFormElement>('input, select, textarea'))
.filter(element => element.name)
.reduce<FormJson>((json, element) => {
json[element.name] = element.type === 'checkbox' ? element.checked : element.value;
return json;
}, {});
To serialize your form you can do this (note that I added an onsubmit in the form tag):
HTML and JavaScript:
function serializeForm(e) {
e.preventDefault(); // prevent the page to reload
let form = e.target; // get the form itself
let data = new FormData(form); // serialize input names and values
let objSerializedForm = {}; // creating a new object
for (let [name, value] of data) { // iterating the FormData data
objSerializedForm[name] = value; // appending names and values to obj
}
console.log(objSerializedForm);
}
<form action="#" method="post" onsubmit="serializeForm(event)">
<div>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</div>
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" />
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
Than you can do whatever you want with your objSerializedForm, getting each value by calling objSerializedForm.name.

Two parameters on a function

I'm trying to make a button onclick event jump to another function if input fields is empty. The function inside the if-statement should have two parameter(one array, one string variable). The function is looping trough all input elements and check if they have a value, if not then add text to a variable that later on is assign to a p-element with .innerHTML.
It worked with only the input parameter, but when I tried to add msg, it stopped working. Maybe it's a simple reason, but I am new to this.
How can I make this work?
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
var msg = "";
btnCreate.onclick = function() {
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
emptyInputs(inputs,msg);
}
message.innerHTML = msg;
}
function emptyInputs(input,text) {
for(var i = 0; i < input.length; i++) {
if (input[i].value === "") {
if(!text) {
missing();
}
text += "- " + input[i].name + "<br />";
}
function missing() {
text = "<strong>Please type in:</strong> <br />";
}
}
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>
You were very close to solving your problem. The only thing is, JavaScript doesn't have ouput params.
When you pass an object or array you can modify the content and those changes will be reflect in your calling method. But this doesn't work for strings. Whatever the value of the string is when you use it as a param to call your method, it will still be the value no matter what your method does to it.
var
array = ['hello'],
object = { hello: true },
string = 'hello';
function modifyArray(inputArray) {
inputArray.push('bye');
}
function modifyObject(inputObject) {
inputObject.bye = true;
}
function modifyString(inputString) {
inputString += ', bye';
}
modifyArray(array);
modifyObject(object);
modifyString(string);
// This will print hello and bye
console.log('Content of array after calling method: ', array);
// This will print hello and bye
console.log('Content of object after calling method: ', object);
// This will just print hello
console.log('Content of string after calling method: ', string);
To solve your problem, create a text string inside the method that builds the error message and return that string as the method result.
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
btnCreate.onclick = function() {
var
// Initialize the error message to an empty string.
msg = '';
// Check if either of the inputs is empty...
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
// ... and get a custom message prompting the user to fill in the empty data.
msg = emptyInputs(inputs);
}
// Display the error message, or clear it when msg is an empty string.
message.innerHTML = msg;
}
function emptyInputs(input) {
// Initialize the error text.
var
missingPrompt = "<strong>Please type in:</strong> <br />",
text = '';
// Iterate over the provided input elements.
for(var i = 0; i < input.length; i++) {
// Check if the value of the current input is an empty string...
if (input[i].value === "") {
// ... check if the error text is still empty...
if(text === '') {
// ... and if it is start with a default message.
text = missingPrompt;
}
// ... add the field name to the error message.
text += "- " + input[i].name + "<br />";
}
}
// Return the error message.
return text;
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>
Here is the code without msg parameter, and it's working just fine.
var assignment = document.getElementById("assignment");
var inputs = assignment.getElementsByTagName('input');
var btnCreate = document.getElementById("submit");
var message = document.getElementById("message");
var msg = "";
btnCreate.onclick = function() {
msg = "";
if (inputs[0].value === "" || inputs[1].value === "" || inputs[2].value === "") {
emptyInputs(inputs);
}
message.innerHTML = msg;
}
function emptyInputs(input) {
for(var i = 0; i < input.length; i++) {
if (input[i].value === "") {
if(!msg) {
missing();
}
msg += "- " + input[i].name + "<br />";
}
function missing() {
msg = "<strong>Please type in:</strong> <br />";
}
}
}
<section id="assignment">
<h1>Add new user</h1>
<form id="newUser">
<div class="inputGroup">
<label for="username">Username</label>
<input type="text" id="username" name="username" />
</div>
<div class="inputGroup">
<label for="password">Password:</label>
<input type="password" id="password" name="password"/>
</div>
<div class="inputGroup">
<label for="passwordConfirm">Confirm password:</label>
<input type="password" id="password2Confirm" name="confirmPassword"/>
</div>
<button id="submit" type="button">Opprett</button>
</form>
<p id="message"></p>
</section>

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Categories

Resources