Convert input fields to Json in javascript - javascript

I would like to get a json result from my input fields.
Json Result
[{ScheduledVisit: "09/06/2017 12:00 AM", Company: "ABC Corp.", ContactPerson: "Someone"}]
The reason for that is because I want it to fit my class of
public class ScheduleVisit
{
[Required(ErrorMessage = "* Required")]
public DateTime ScheduledVisit { get; set; }
public string Company { get; set; }
public string ContactPerson{ get; set; }
}
I do not want to use the $("inputForm").serialize(); because I want to learn how to do this manually.
Below is my input form
<div class="col_half">
<input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
</div>
<div class="col_half col_last">
<input type="text" name="company" class="sm-form-control border-form-control" placeholder="company" id="company" />
</div>
<div class="col_two_third">
<input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" />
</div>
Please help. Thank you.

You can iterate <form> .elements, set each .name and .value as property and values of a FormData() object which can be submitted to server using fetch() or XMLHttpRequest(), or set properties and values at a JavaScript object which can be passed to JSON.stringify()
const form = document.forms[0];
form.onsubmit = e => {
e.preventDefault();
const fd = new FormData();
const props = {};
for (let element of form.elements) {
if (element.type !== "submit") {
props[element.name] = element.value;
fd.append(element.name, element.value);
}
}
for (let [key, prop] of fd) {
console.log(key, prop)
}
const json = JSON.stringify(props);
console.log(json);
}
<form>
<div class="col_half">
<input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
</div>
<div class="col_half col_last">
<input type="text" name="company" class="sm-form-control border-form-control" placeholder="company" id="company" />
</div>
<div class="col_two_third">
<input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" />
</div>
<input type="submit">
</form>

You can make object constructors that resemble your backend code. Here, I am serializing the inputs into a scheduleVisit object.
function scheduleVisit(obj) {
this.scheduledVisit = obj.scheduledVisit;
this.company = obj.company;
this.contactPerson = obj.contactPerson;
}
document.getElementById('button').addEventListener('click', function() {
var scheduledVisit = document.getElementById('ScheduledVisit').value;
var company = document.getElementById('company').value;
var contactPerson = document.getElementById('contact').value
var visit = new scheduleVisit({
scheduledVisit: scheduledVisit,
company: company,
contactPerson: contactPerson
});
console.log(JSON.stringify(visit));
});
<div class="col_half">
<input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" id="ScheduledVisit" />
</div>
<div class="col_half col_last">
<input type="text" name="company" class="sm-form-control border-form-control" placeholder="company" id="company" />
</div>
<div class="col_two_third">
<input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" id="contact" />
</div>
<button id=button>Submit</button>

You can assign the value of your inputs to an object manually. See below snippet for example. You can then serialize the object into a JSON formatted string.
let obj = {};
obj.ScheduledVisit = document.getElementById("ScheduledVisit").value;
obj.Company = document.getElementById("company").value;
obj.Contact = document.getElementById("contact").value;
console.log(obj);
let jsonStringObj = JSON.stringify(obj);
console.log(jsonStringObj);
<div class="col_half">
<input type="text" name="ScheduledVisit" placeholder="Scheduled Visit" class="sm-form-control border-form-control datetimepicker" value="testVisit" id="ScheduledVisit" />
</div>
<div class="col_half col_last">
<input type="text" name="company" class="sm-form-control border-form-control" placeholder="company" value="testCompany" id="company" />
</div>
<div class="col_two_third">
<input type="text" name="contactPerson" placeholder="Contact Person" class="sm-form-control border-form-control" value="testContact" id="contact" />
</div>

Using pure javascript you can do JSON.stringify(yourInputValu) to convert any javascript object to JSON

If your input form is that simple and you don't want a more generic solution, you could do it pretty easily with:
function get( id ) { return document.getElementById(id).value; }
var json = JSON.stringify({
ScheduledVisit: get('ScheduledVisit'),
Company: get('company'),
Contact: get('contact')
});

Related

getElementById return empty values so post empty values

I'm working with DOM and web API to POST some information about the company like name, worker's name.
But when I write something in the input DOM can't reach the value and return empty so I post an empty object.
That looks like :
adress: ""
companyName: ""
contactName: ""
contactTitle: ""
My form block:
<form>
<div class="form-group">
<label for="">Company Name</label>
<input
type="text"
class="form-control"
id="companyName"
placeholder="Company Name!"
/>
</div>
<div class="form-group">
<label for="">Contact Name</label>
<input
type="text"
class="form-control"
id="contactName"
placeholder="Contact Name!"
value=""
/>
</div>
<div class="form-group">
<label for="">Contact Title</label>
<input
type="text"
class="form-control"
id="contactTitle"
placeholder="Contact Title!"
/>
</div>
<div class="form-group">
<label for="">Country</label>
<input
type="text"
class="form-control"
id="inputCountry"
placeholder="Country!"
/>
</div>
</form>
And my JS code:
'use strict';
let inputCompanyName = document.getElementById('companyName');
let inputContactName = document.getElementById('contactName');
let inputContactTitle = document.getElementById('contactTitle');
let country = document.getElementById('inputCountry');
const btnSubmit = document.getElementById('submit');
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
btnSubmit.addEventListener('click', e => {
e.preventDefault();
axios
.post('https://northwind.vercel.app/api/suppliers', newCompany)
.then(res => {
console.log('Response', res.data);
alert('Success!');
});
});
I tried innerHTML and innerText and form method but I cant solve this problem.
You're reading the values immediately upon loading the page, long before the user has had a chance to enter any values.
Instead, read the values in the click event:
btnSubmit.addEventListener('click', e => {
let newCompany = {
companyName: inputCompanyName.value,
contactName: inputContactName.value,
contactTitle: inputContactTitle.value,
adress: country.value,
};
// the rest of the click handler logic...
});

Why data passed from frontend using ajax shows NonType in view function in Django

I have created a form in html which take some value from user on clicking submit button a JavaScript function is called which passes data using ajax to Django server. But instead of getting data in view function it shows NoneType error on backend.
My html form:-
<div class="cropDetail">
<form method="post">
{% csrf_token %}
<div class="form__group">
<label htmlFor="name" class="form__label"> Nitrogen </label>
<input type="number" id="nitrogen" name="nitrogen" class="form__input" required />
<p class="error"></p>
</div>
<div class="form__group">
<label htmlFor="name" class="form__label"> Potassium </label>
<input
type="number"
id="potassium"
class="form__input"
name="potassium"
required
/>
<p class="error"></p>
</div>
<div class="form__group">
<label htmlFor="name" class="form__label"> Phosphorus </label>
<input
type="number"
id="phosphorus"
class="form__input"
name="phosphorus"
required
/>
<p class="error"></p>
</div>
<div class="form__group">
<label htmlFor="name" class="form__label"> PH </label>
<input type="number" id="ph" class="form__input" name="ph" required />
<p className="error"></p>
</div>
<div class="form__group">
<label htmlFor="name" class="form__label"> Rainfall </label>
<input type="number" id="rainfall" class="form__input" name="rainfall" required />
<p class="error"></p>
</div>
<div class="form__group">
<label htmlFor="name" class="form__label"> City </label>
<input type="text" id="city" class="form__input" name="city" required />
<p class="error"></p>
</div>
<div class="form__actions">
<button onclick="passdata()">Submit</button>
</div>
</form>
</div>
My JavaScript function:-
const nitro = document.getElementById("nitrogen");
const potass = document.getElementById("potassium");
const phos = document.getElementById("phosphorus");
const phi = document.getElementById("ph");
const rain = document.getElementById("rainfall");
const cityi = document.getElementById("city");
function passdata(event) {
event.preventDefault();
const usernitrogen = nitro.value;
const userpotassium = potass.value;
const userphosphorus = phos.value;
const userph = phi.value;
const userrainfall = rain.value;
const usercity = cityi.value;
console.log(usernitrogen);
$.ajax({
type:"POST",
url: "crop_prediction/",
data: {
'nitrogen': usernitrogen,
'potassium': userpotassium,
'phosphorus': userphosphorus,
'ph': userph,
'rainfall': userrainfall,
'city': usercity,
},
success: function () {
alert(`Thankyou for your feedback`);
},
});
};
urls.py:-
from django.urls import path, include
from .import views
urlpatterns = [
path('', views.home),
path('crop_prediction/', views.crop_prediction),
path('crop_detail/', views.crop_info)
]
Views function:-
def crop_prediction(request):
global resultJson, firebase
resultJson = dumps({"error": "some error"})
if request.method == "POST":
N = float(request.POST.get("nitrogen"))
P = float(request.POST.get("phosphorus"))
K = float(request.POST.get("potassium"))
ph = float(request.POST.get("ph"))
rainfall = float(request.POST.get("rainfall"))
city = request.POST.get("city")
resultJson = dumps({"error": "some error occured"})
if weather_fetch(city) != None:
temperature, humidity = weather_fetch(city)
data = np.array([[N, P, K, temperature, humidity, ph, rainfall]])
my_prediction = pickle.load(
open('CropRecommendation\model\model.pkl', 'rb'))
final_prediction = my_prediction.predict(data)
value = "rice"
firebase = firebase.FirebaseApplication(
'https://e-farma-5dc42-default-rtdb.firebaseio.com/')
predicted_crop_info = firebase.get(value, None)
predicted_crop_info["crop"] = value
resultJson = dumps(predicted_crop_info)
return render(request, "Efarma/index.html", {"result": resultJson})
# return render(request, 'efarma/cropDetail.html', {"result": resultJson})
else:
return render(request, "Efarma/index.html", {"result": resultJson})
error:-
enter image description here

How clear form after submit

I made some little project with adding element to DOM. It's working but I don't know how to clear form after submit. I need to assign a blank value? At what point? Sorry, Im new, please don't bite. Thanks.
const addElement = (e, node, txt, attr, value) => {
e.preventDefault();
const element = document.createElement(node);
if(txt){
const text = document.createTextNode(txt);
element.appendChild(text);
}
if(attr){
element.setAttribute(attr, value)
}
document.querySelector('.content').appendChild(element);
}
const addForm = document.querySelector('.form--add');
addForm.addEventListener('submit', (e) => addElement(
e,
addForm.elements.node.value,
addForm.elements.text.value,
addForm.elements.attr.value,
addForm.elements.value.value,
));
<div class="form-container">
<form class="form form--add">
<h1 class="form__title">Add element to DOM</h1>
<input type="text" class="form__input" name="node" placeholder="element html" required>
<input type="text" class="form__input" name="text" placeholder="txt in element html">
<input type="text" class="form__input" name="attr" placeholder="attr" required>
<input type="text" class="form__input" name="value" placeholder="attr value" required>
<button class="form__button">Add element</button>
</form>
<form class="form form--search">
<h1 class="form__title">Search DOM</h1>
<input type="text" class="form__input" placeholder="szukana nazwa elementu" required>
<input type="submit" class="form__button" value="znajdź i pokaż informacje">
</form>
</div>
<div class="result"></div>
<div class="content"></div>
<footer class="footer">Stopka</footer>
<script src="main.js"></script>
Thank you
Try addForm.reset()
or
declare an id for suppose form_id then paste below code after submit
document.getElementById("form_id ").reset();
addForm.addEventListener('submit', (e) => addElement(
e,
addForm.elements.node.value,
addForm.elements.text.value,
addForm.elements.attr.value,
addForm.elements.value.value,
addForm.getElementsByTagsName('input').forEach(el => {
el.value = ''
})
));

How do I group inputs in Local storage to be one "Event" categorized by my Date time input

In my app I collect information from the user and store it in Local storage using javascript like this.
Event Name (1 to 20 characters):
<input type="text" id="eventname" name="eventname" required
minlength="1" maxlength="20" size="20">
<label for="datetime">Event Date and Time:</label>
<input type="datetime-local" id="date" name="date" required
minlength="1" maxlength="20" size="20">
<label for="eventlocation">Event Location (1 to 20 characters):</label>
<input type="text" id="location" name="location" required
minlength="1" maxlength="20" size="20">
<label for="notes">Notes (0 to 50 characters): </label>
<input type="text" id="notes" name="notes" required
minlength="0" maxlength="50" size="50">
<script src="app.js"></script>
I then have an app.js document which puts it into local storage
const locationTxt = document.querySelector('#location');
locationTxt.addEventListener('change', (event) => {
localStorage.setItem('location', event.target.value);
function getSavedData() {
console.log('location', localStorage.getItem('location'));
(except i have these fucntions for each of the inputs.)
How Would i go about taking all these inputs in locale storage and displaying it as 1 event that is able to be categorized by time?
One way would be to store event data in an object:
{
'01-02-1900': [
... // Array of events
],
'01-01-1900': [
... // Array of events
],
...
}
And then using JSON.parse and JSON.stringify to read/write to localStorage. 😊
For instance:
/**
* This override localStorage in Stack Snippet
*/
const customStorage = { data: {} };
customStorage.getItem = index => customStorage.data[index] || null;
customStorage.setItem = (index, payload) =>
(customStorage.data[index] = payload);
/**
* Replace customStorage with localStorage below.
*/
const inputs = document.querySelectorAll("input");
const storageIndex = "myTestStorage";
const storeInLocal = formData => {
const { date, event } = formData;
const toStore = JSON.parse(customStorage.getItem(storageIndex)) || {};
if (!toStore[date]) toStore[date] = [];
toStore[date].push(event);
customStorage.setItem(storageIndex, JSON.stringify(toStore));
};
const readForm = () => {
let values = {};
inputs.forEach(({ name, value }) => {
values[name] = value;
});
const { date, eventname, location, notes } = values;
return {
date,
event: {
eventname,
location,
notes
}
};
};
const outputStorage = () => {
const storage = customStorage.getItem(storageIndex) || "";
document.getElementById("output").innerText = storage;
};
document.getElementById("eventForm").addEventListener("submit", e => {
e.preventDefault();
const formData = readForm();
storeInLocal(formData);
outputStorage();
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Store form data in localStorage</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
rel="stylesheet"
/>
<style>
pre {
white-space: pre-wrap;
}
</style>
</head>
<body>
<main id="app" role="main" class="container">
<form id="eventForm">
<div class="form-group row">
<label for="eventname">Event Name</label>
<div class="col-sm-6">
<input
type="text"
id="eventname"
name="eventname"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="datetime">Event Date and Time:</label>
<div class="col-sm-6">
<input
type="datetime-local"
id="date"
name="date"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="eventlocation">Event Location</label>
<div class="col-sm-6">
<input
type="text"
id="location"
name="location"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="notes">Notes</label>
<div class="col-sm-6">
<input
type="text"
id="notes"
name="notes"
required
minlength="0"
maxlength="50"
/>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<h1 class="h4">Output</h1>
<p>Hit "save" multiple times, and change the date occasionally.
<p>
<pre id="output"></pre>
</p>
</main>
</body>
</html>

appending a json file with javascript

I have an existing json file (data.json) that I would like to append with information captured from a form.
I have the form outputting json but I am not sure how to go about getting this to add to my existing json file.
So the form looks like this:
<form id="test" action="#" method="post">
<div class="form-group">
<label for="department">Department:</label>
<input class="form-control" type="text" name="department" id="department" />
</div>
<div class="form-group">
<label for="role">Role title:</label>
<input class="form-control" type="text" name="role" id="role" />
</div>
<div class="form-group">
<label for="pay_status">Pay status:</label>
<input class="form-control" type="text" name="pay_status" id="pay_status"/>
</div>
<div class="form-group">
<label for="typicalposts">Typical number of posts in a year:</label>
<input class="form-control" type="text" name="typicalposts" id="typicalposts"/>
</div>
<div class="form-group">
<label for="email">Restrictions:</label>
<input class="form-control" type="text" name="restrictions" id="restrictions" />
</div>
<div class="form-group">
<label for="recruitment_date">Recruitment date:</label>
<input class="form-control" type="date" name="recruitment_date" id="recruitment_date" />
</div>
<div class="form-group">
<label for="weblink">Weblink:</label>
<input class="form-control" type="text" name="weblink" id="weblink" />
</div>
<div class="text-center">
<p>
<input type="submit" value="Send" class="btn btn-primary center_block" />
</p>
</div>
</form>
<pre id="output" ></pre>
And the js I have to turn this data to json is:
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
var output = document.getElementById( "output" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
output.innerHTML = json;
}, false);
});
})();
This shows the json in #output for the moment, I would like what is being shown here to be appended to data.json instead
Thanks for your help
My files are hosted on a server that I dont have access too which is why I would like to do this via js
So BBC News have an HTML document at http://www.bbc.co.uk/news. Would it be a good idea if it was possible for my browser to edit the page and save it back to the server?
It is absolutely impossible to do what you want, because it would require that any old browser could edit any old file on any old server.
In order to change data on the server, you have to have the cooperation of the server (which you say you don't have).

Categories