FormData - Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement - form-data

Could someone tell me why I always get a following error?
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
My HTML:
<form role="form" id="uploadSortimentReport" enctype="multipart/form-data">
<div class="card-body">
<div class="form-group">
<label>XML file</label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="report">
<label class="custom-file-label">choose file</label>
</div>
</div>
</div>
<div class="form-group">
<label>Country</label>
<select name="country" class="form-control">
<option value="">choose</option>
<option value="sk">Slovak</option>
<option value="cz">Czech</option>
</select>
</div>
</div>
<div class="card-footer">
<button type="submit" name="uploadReport" class="btn btn-info" id="uploadButton">Upload</button>
</div>
</form>
My JS (I know that ajax is not completed, but it shouldn't be throw an error I think)
$.validator.setDefaults({
submitHandler: function () {
$('#uploadButton').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Processing');
var fd = new FormData($('#uploadSortimentReport'));
}
});
$('#uploadSortimentReport').validate({
rules: {
report: {
required: true,
extension: "xml"
},
country: {
required: true
}
},
messages: {
report: {
required: "Please choose file.",
extension: "Only XML file is accepted."
},
country: {
required: "Please choose country."
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
I tried to do everything. Nothing helped.
Thank you.

var fd = new FormData($('#uploadSortimentReport')[0]);
Try this, because $('#uploadSortimentReport') is a jquery wrapper object. But class formData requires a vanilla js dom object.
For More Info : What does $(selector)[0] mean in jQuery?

Related

Every row is executed twice

I have found a bug - and I haven't found any solution to this.
I have a code in ASP.NET Core (using VSPro 2019 16.5.0):
public IActionResult CreateSubGroup(MyClass model, string returnUrl = null)
{
if (ModelState.CreateMyClassValidation())
{
if (!db.MyClass.Where(x => x.Title == model.Title).Any())
{
ViewData["ReturnUrl"] = returnUrl;
var code = new MyClass { Title = model.Title, IdGroup = model.IdGroup, GroupCode = model.GroupCode};
db.MyClass.Add(code);
var result = db.SaveChanges();
if (result > 0)//if there was no issue (at least one row was changed)
{
this.AddNotification(MessagesHandler.Success, $"Item\"{model.Title}\" was successfully created.");
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" cannot be created.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"Item \"{model.Title}\" already exists.");
}
}
else
{
this.AddNotification(MessagesHandler.Error, $"ErrorMessage.");
}
return RedirectToLocal(returnUrl);
}
Creating of new Item always crashes with unique code exception from DB - During debuging I have found, that every row is executed twice (and I don't know why??) - so also the row db.SaveChanges() is executed twice and that's why I got this exception.
Second bad thing is, that not even the first attempt to save database is not executed (= new Item is not created in DB).
Have you seen this error?
EDIT:
I have found, that it happens only when data are posted from view with JS/AJAX (from modal window)
Here is the code for sending data:
<div class="modal fade" id="ModalWindow" tabindex="-1" role="dialog" aria-labelledby="ModalForm" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="ModalForm" action="" method="post" class="validator">
<div class="modal-body">
<div class="form-group">
<label asp-for="Id"></label>
<input class="form-control" asp-for="Id" value="" readonly data-val="false">
<div class="form-text text-muted small">ID cannot be changed!</div>
</div>
<div class="form-group">
<label asp-for="Title"></label>
<input class="form-control mlfb-create" asp-for="Title" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="Title"></span>
</div>
<div class="form-group">
<label asp-for="IdGroup"></label>
<select class="selectpicker form-control" asp-for="IdGroup" data-live-search="true" data-style="btn-info" tabindex="#(++tabindex)">
#if (data?.GroupData != null)
{
#foreach (var item in data?.GroupData)
{
<option value="#(item.Id)">#item.Title</option>
}
}
</select>
</div>
<div class="form-group">
<label asp-for="GroupCode"></label>
<input class="form-control mlfb-create" asp-for="GroupCode" placeholder="Title" value="" autofocus tabindex="#(++tabindex)">
<span class="text-danger small" asp-validation-for="GroupCode"></span>
</div>
</div>
<div class="text-center modal-footer">
<button type="submit" class="btn btn-success _modal-buttton-save" tabindex="#(++tabindex)"><i class="fas fa-check mr-2"></i><span>Save</span></button>
<button type="reset" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#section scripts {
<script>
$(function () {
"use strict";
$(document).on('click', '._createSubFormButton', function () {
$('#ModalWindow').modal('show');
$('.modal-title').text('Creating of subgroup');
$('.modal-buttton-save span').text('Create');
$('#ModalForm').attr('action', '/MyCode/CreateSubGroup/?returnurl=' + window.location.href);
});
// Edit form
$(document).on('click', 'tr ._editSubFormButton', function () {
$('#ModalWindow').modal('show');
var $tr = $(this).closest('tr');
var Id = $tr.find('._Id').text();
var Title = $tr.find('._Title').text();
var IdGroup = $tr.find('._IdGroup').text();
var GroupCode = $tr.find('._GroupCode').text();
$('.modal-title').text('Editing of subgroup');
$('#ModalForm').attr('action', '/MyCode/EditSubGroup/' + Id + '?returnurl=' + window.location.href);
$('#Id').val(Id);
$('#Title').val(Title);
$('#GroupCode').val(GroupCode);
});
// form validation reset during closing modal form
$('#ModalWindow').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
$('#IdGroup').load();
$('.form-group .is-invalid').each(function () { $(this).removeClass('is-invalid'); });
$('.form-group .is-valid').each(function () { $(this).removeClass('is-valid'); });
$('.form-text.text-danger').each(function () { $(this).removeClass('text-danger'); });
$('.form-text.text-success').each(function () { $(this).removeClass('text-success'); });
$('.invalid-feedback').each(function () { $(this).remove(); });
});
$(document).on('submit', '#ModalForm', function (e) {
var form = $('#ModalForm');
if (form.valid()) {
console.log(form.serializeArray());
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: form.serializeArray()
}).done(function () {
console.log('done');
$tr.find('._Number').text();
var $tr = $(this).closest('tr');
})
.fail(function () {
console.log('fail');
});
$('#ModalWindow').modal('hide');
}
});
error I got:
Have you tried debugging this code? Debugging with setting breakpoints and stepping through the code would help you find what is wrong with this code.

I have problem in my Vue.js code, i am getting errors while inserting data into database

I am getting 3 different errors while submitting the data from the form
first error is : [Vue warn]: Error in mounted hook: "TypeError: this.getAllUsers is not a function"
and then if I test form validation without typing anything validation works but i get this error: [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'preventDefault' of undefined"
and then i fill in all the fields and click the submit button then i get this error: [Vue warn]: Error in v-on handler: "ReferenceError: axios is not defined"
Note: my API works perfectly
here's my code
this is the form
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<form id="app" #submit="saveUser" method="post" novalidate="true">
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx">TRX Address No.</label>
<input
id="trx"
class="form-control trx-address-nooverflow"
v-model="myAddress"
type="text"
name="TRX Address"
readonly
>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
id="name"
class="form-control"
v-model="name"
type="text"
name="name"
>
</div>
<div class="form-group col-md-3">
<label for="name">Country</label>
<country-select
id="Country"
class="form-control"
v-model="country"
:country="country"
topCountry="US" />
</div>
<div class="form-group col-md-3">
<label for="email">Email ID</label>
<input
id="email"
class="form-control"
v-model="email"
type="email"
name="email"
>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="email">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="mobile_no"
type="text"
name="mobile"
>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</b-container>
</template>
this is the script
<script>
export default{
data(){
return{
errorMessage: "",
successMessage: "",
errors: [],
trx_no: "",
name: "",
country: "",
email: "",
mobile_no: "",
myAddress: "",
newUser: {trx_no: "", name: "", country: "", email: "", mobile: ""}
}
},
mounted: function(){
this.getAllUsers();
},
methods: {
saveUser(event){
event.preventDefault()
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('http://localhost:8888/vue-and-php/public/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx_no: "", name: "", country: "", email: "", mobile: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
}
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
if (!this.name) {
this.errors.push("Name Required.");
}
if (!this.country) {
this.errors.push("Country Required.");
}
if (!this.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.mobile_no) {
this.errors.push("Phone Number Required.");
}
if (!this.errors.length) {
return true;
}
e.preventDefault();
},
validEmail: function (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>
I am also posting my PHP code just for reference
<?php
//Import Database
require 'base.php';
if(isset($_GET['action'])){
$action = $_GET['action'];
}
//create
if($action == 'update'){
$trx_number = $_POST['trx'];
$name = $_POST['name'];
$country = $_POST['country'];
$email = $_POST['email'];
$mobile = $_POST['mobile_no'];
$result = $con->query(" INSERT INTO `update_information` (`id`, `trx_no`, `name`, `country`, `email`, `mobile_no`) VALUES (null,'$trx_number','$name','$country','$email','$mobile') ");
if($result){
$res['message'] = "Success";
}else {
$res['error'] = true;
$res['message'] = "Error";
}
$res['update_information'] = $update_information;
}
$con->close();
//encoding into json
echo json_encode($res);
die();
Here are the solutions to your errors
There is no method called getAllUsers You need to define one or stop calling it in your code.
Remove the event.preventDefault() from your code ande replace #submit="saveUser" with #submit.prevent="saveUser" in your form.
Import axios into your component with import axios from 'axios'. NOTE: Make sure axios ins installed in your project

I am trying to build a contact form in Vue.js and Php but i am getting errors i am not quite sure how to solve this problem

I am trying to build a contact form in vue js and PHP but its not working and i am getting erros i used internet sources to build this form watched many tutorials i am not sure how to solve this. And i am very new to vuejs any kind of help would be appreciated
here's my code
<script>
export default{
data(){
return{
errorMessage: "",
successMessage: "",
errors: [],
trx_no: "",
name: "",
country: "",
email: "",
mobile_no: "",
myAddress: "",
newUser: {trx_no: "", name: "", country: "", email: "", mobile: ""}
}
},
mounted: function(){
this.getAllUsers();
},
myAddress: function() {
return this.$store.state.myAddress;
},
methods: {
saveUser: function(){
//console.log(this.newUser);
var formData = this.toFormData(this.newUser);
axios.post('http://localhost:8888/vue-and-php/public/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx_no: "", name: "", country: "", email: "", mobile: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
//if (!this.trx_no) {
// this.errors.push("TRX Address Required.");
//}
if (!this.name) {
this.errors.push("Name Required.");
}
if (!this.country) {
this.errors.push("Country Required.");
}
if (!this.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.mobile_no) {
this.errors.push("Phone Number Required.");
}
if (!this.errors.length) {
return true;
}
e.preventDefault();
},
validEmail: function (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>
and this is the contact form
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<form
id="app"
#submit="checkForm"
method="post"
novalidate="true"
>
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx">TRX Address No.</label>
<input
id="trx"
class="form-control trx-address-nooverflow"
v-model="myAddress"
type="text"
name="TRX Address"
readonly
>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
id="name"
class="form-control"
v-model="name"
type="text"
name="name"
>
</div>
<div class="form-group col-md-3">
<label for="name">Country</label>
<country-select
id="Country"
class="form-control"
v-model="country"
:country="country"
topCountry="US" />
</div>
<div class="form-group col-md-3">
<label for="email">Email ID</label>
<input
id="email"
class="form-control"
v-model="email"
type="email"
name="email"
>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="email">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="mobile_no"
type="text"
name="mobile"
>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" value="submit" class="btn btn-btn btn-grad btn-submit" #click="saveUser();"/>
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</b-container>
</template>
Thanks in advance and #respect
NOTE: API is working fine I've tested it in Postman
I don't know what errors you get, but I see a problem with how the form is submitted.
Some changes I recommend:
The form:
<form id="app" #submit="saveUser" method="post" novalidate="true"> ... </form>
The button:
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
The saveUser method:
saveUser(event){
event.preventDefault()
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('http...')
// rest of the code
}
}
Can't test it as I don't have the project, but this should help.
However, instead of the above approach, I would recommend to do the validation at input level and let each input component deal with its own validation logic and messages. The submit button to become enabled only when no errors exist in the form. There are many component libraries for this. For the user would be much better experience to see the errors in real time than with the above way to have a list of errors upon trying to submit the form.

VueJs: How to create a select where options come from a query to other model

I'm new on VueJs and I don't know why I have the following problem:
I'm creating a view called Owners.vue where I show pub owners. In UpdateProfile.vue I show the owner data and here is where I have my problem: I'd like to build a select where the options are the possible pubs stored in my table "pubs":
My vue component is as follows:
UpdateProfile.vue
<template>
<confirm title="Edit User" ok="Save user" :show="show"
v-on:save="save"
v-on:close="close">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="User name" v-model="data.name">
</div>
</div>
<div class="field">
<label class="label">Lastname</label>
<div class="control">
<input class="input" type="text" placeholder="last name" v-model="data.lastname">
</div>
</div>
<div class="field">
<label class="label">Email</label>
<div class="control">
<input class="input" type="email" placeholder="email" v-model="data.email">
</div>
</div>
<!--Owner Pubs-->
<div class="field">
<label class="label">Pubs</label>
<div v-for="pub in data.userPubsOwned" class="control">
<input class="input" type="text" placeholder="Pub tapps" v-model="pub.name">
<div class="button is-danger" #click="deletePubFromOwner(pub.id)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete</span>
</div>
</div>
<br>
</div>
<!--Owner Pubs-->
<!--Add Pubs to Owner-->
<div class="field">
<label class="label">Add new Pub</label>
<div class="select">
<select v-model="pubs">
<option v-for = "pub in pubs" :value="pub.id" >{{pub.name}}</option>
</select>
</div>
<br>
<br>
<div class="button is-info" #click="addPubToOwner()">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Add Tapp</span>
</div>
</div>
<!--Add Pubs to Owner-->
</confirm>
import User from "../../models/user";
export default {
props: {
show: Boolean,
data: Object,
},
data() {
return {
selected: null,
data: new User(),
pubs: [],
pub: new Pub(),
}
},
computed: {
},
methods: {
save() {
this.$emit('save', this.data);
},
close() {
this.$emit('close');
},
hasRootPermissionsAndIsNotRoot() {
return this.CONSTANTS.hasRootPermissions() && this.data.permissions !== this.CONSTANTS.ROOT_USER.permissions;
},
addPubToOwner(){
this.api.post('/owners/' + this.data.id + '/' + this.selected).then(response => {
this.data = response.data;
});
},
deletePubFromOwner(ownerpub) {
this.api.delete('/owners/' + this.data.id + '/' + ownerpub).then(response => {
this.data = response.data;
});
},
}
}
I just need to show all the pubs stored in my table pub...do I have to create a function? And how it would be?
Thanks a lot for your help!!
Yes, create a method in the mounted() section. I use a similar process to show all of the flavors/prices of a product in a shopping cart. Here is my code that you can use and hopefully extrapolate your answer from:
Mounted function to load upon vue mount
mounted: function() {
this.getPrice();
},
getPrice() function:
getPrice: function(){
axios.post('/getproductinfo', this.$data.model)
.then((response) => {
console.log(response);
this.display_name = response.data.display_name;
this.price = '$' + response.data.price;
})
.catch(error => {
this.errors.record(error.response.data.errors);
});
},
And finally the code in your view blade file
<select class="centerSelect" v-show="!loading && ordering" ref="quantitySelect" v-model="model.id" name="code_id" #change="getPrice">
#foreach ($code as $item)
<option value="{{$item->id}}">{{$item->display_name}}</option>
#endforeach
</select>

Send form data via AJAX to multiple PHP files

So, i have no clue if what i want to do is even possible, but i tried and failed ;P
<script>
$("#submitdata").submit(function()
{
var datefrom=document.getElementById( "datefrom" );
var dateto=document.getElementById( "dateto" );
var dropdown=document.getElementById( "dropdown" ).value;
alert (dropdown);
if (dropdown === "0") {
alert ("Please choose first!");
} else if (dropdown === "1") {
$.ajax({
type: 'post',
url: 'showData.php',
data: {
datefrom: datefrom,
dateto: dateto,
choice: dropdown
},
success: function () {
$('#inner').load('#inner');
}
});
return false;
} else if (dropdown === "2") {
} else if (dropdown === "3") {
} else if (dropdown === "4") {
}
});
</script>
<form method="post" id="submitdata" name="submitdata">
<div class="row uniform">
<div class="12u 12u$">
<input type="text" name="datefrom" id="datefrom" value="" placeholder="From" />
</div>
<div class="12u 12u$">
<input type="text" name="dateto" id="dateto" value="" placeholder="To" />
</div>
<div class="12u$">
<div class="select-wrapper">
<select name="dropdown" id="dropdown">
<option value="0">- Choose -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
<div class="12u$">
<ul class="actions">
<li><input type="submit" id="btnSubmit" value="Submit" class="special" /></li>
<li><input type="reset" value="Reset" /></li>
</ul>
</div>
</div>
</form>
I want to send the data to different files, depending on what the user chooses in the form dropdown (if that is possible).
I get the alerts and everything is fine but it just jumps into the other "elseif's" even tho the value of dropdown is "0".
Any idea how to solve this?
I found the solution eventually:
if(!datumvon.value){
alert("Watch out");
}
else if(dropdown === "0"){
alert("Do Step 1 first");
}else if(dropdown >= "1") {
$.ajax({
type: 'post',
url: 'showData.php',
data: {
datumvon: datumvon,
datumbis: datumbis,
dropdown: dropdown
},
success: function () {
$('#inner').load('#inner');
}
});
}else {
alert("Error");
}
return false;
The problem was some kind of syntax error in the javascript part. Thanks for the help

Resources