JSON Data into form fields - javascript

I'm new to Javascript and Jquery so please excuse my ignorance. I'm trying to get my form fields to auto populate city and state based on zip code using JSON data I am pulling from an online .asp database. I am getting a successful JSON response with data that I can view in my dev tools window, but cannot get it to populate the fields on my form.
My Code is:
$(function() {
var cache = {};
var container = $("#validate");
var errorDiv = container.find("div.text-error");
/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("City" in data)
{
// Set city and state
container.find("input[name='City']").val(data.City);
container.find("input[name='State']").val(data.State);
}
}
// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();
// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
// Build url
var url = "http://dev.xxx.com/ASPFetchers/GetSPROCAsXML.asp?SPROC=EG_GetZipCodeInfo%20/"+(zipcode)+"/&F=JSON";
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;
// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
My markup on my form is as follows:
<div id="validate">
<label>Zip Code</label>
<input type="text" name="zipcode" id="zipcode" size =" 5" maxlength = "5" />
<div class="text-error"></div>
<label>City</label>
<input type="text" name="City" id="City" />
<label>State</label>
<input type="text" name="State" id="State" />
<script type="text/javascript" src="../zip/includes/zip2.js"></script>
</div>
</div>
The JSON I can view in my dev tools is(based on zipcode 06702):
{"items":[{"City":"WATERBURY","County":"NEW%20HAVEN","State":"CT","StateName":"CONNECTICUT","Latitude":"0.7252836","Longitude":"-1.274794"},
Can anyone help me solve how to get the information from this string and have it populate the "City" and "State" field? Thank You for your time and knowledge.

If you look at the data you posted here, you will need to use the items array inside of your data.
container.find('input[name="City"]').val(data.items[0].City);
container.find('input[name="State"]').val(data.items[0].StateName);

The object that is returned looks is an array of objects.
So first get the items array and refer the 1st item inside it.
function handleResp(data) {
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("City" in data) {
var info = data.items[0];
// Set city and state
container.find("input[name='City']").val(info.City);
container.find("input[name='State']").val(info.State);
}
}

Related

how to pass values from multiple textfields with same name attributes to a variable in form of an array

I am building a form that passes a set of numbers in form of an array to a variable as seen below
var users=["1","2"];
the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below
var users=["1","2"];
var async_request=[];
var responses=[];
for(i in users)
{
// you can push any aysnc method handler
async_request.push($.ajax({
url:'back.php', // your url
method:'post', // method GET or POST
data:{user_name: users[i]},
success: function(data){
console.log('success of ajax response')
responses.push(data);
}
}));
}
$.when.apply(null, async_request).done( function(){
// all done
console.log('all request completed')
console.log(responses);
$( '#responses' ).html(responses[1]);
$( '#responses1' ).html(responses[0]);
});
This works perfectly.
But now I want to make some adjustments to my solution specifically
Im looking to replace the method of passing the numbers to the variable users
from
var users=["1","2"]; // Im looking to replace the method
to this
var users = $('[name="tom[]"]').val(attachArray);
<input type="text" name="tom[]" value="1" /><br>
<input type="text" name="tom[]" value="2" /><br>
but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this
var users=["1","2"];
You mean
const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
return arr[i]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br>
or
$('[name^=tom]').each(function() {
async_request.push($.ajax({
url:'back.php',
method:'post',
data:{user_name: this.value },
You forgot to use input key value :
var users = $('input[name="tom[]"]').val();

How to split and display from string to array for Select2 jquery?

How to split and display from string to array for Select2 jquery? Current string that I get from DB is like this Michael,Anna,Sofea, hence how to split into array as Select2 format will read array to display the information, like this ["Michael","Anna","Sofea"]
Console.log from API reading
Current console.log after split is like below:
But why the selected that come from DB does not appear in Select2 <select> selection?
<div class="col-lg-10 col-sm-8">
<select type="text" class="form-control myClass" id="editOwner" multiple="multiple"></select>
</div>
// To read all users fullname from API
$.ajax ({
...
success: function(response){
for (var i = 0; i < response.data.length; i++) {
$("#editOwner").append($("<option>", {
response: response.data[i].fullname,
text: response.data[i].fullname
}));
}
}
});
// To read current selected user based on what had been stored from DB
function editLayer3(id){
$.ajax({
...
success: function(response){
if (response.status == "Success"){
$("#editOwner").val(response.data[0]["task_owner"]).attr("disabled",false);
var test = response.data[0]["task_owner"];
var results = test.split(",");
$("#editOwner").select2();
}
else {}
},
error: function(e){}
});
// Will redirect to Edit form that contain Submit button
}

Odoo AJAX attachment or images creation into client-side (frontend)

What i know
In a modal creation object i know how add an attachment or image because all <input> are inside a form and when user click the submit button the form action trigger the controller that manage inputs data.
For Example:
<form id="formId" t-attf-action="/my/object/#{slug(object)}/create" method="post" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>
<input type="hidden" name="object" t-att-value="object"/>
<input type="text" name="text" class="o_website_form_input form-control"/>
<input type="file" name="image" class="o_website_form_input form-control" accept="image/*"/>
<input type="submit" class="btn btn-success" value="Create/"/>
</form>
Will trigger the following controller:
#route(['/my/object/<model("object.model"):object>/create'],
type='http', auth="user", methods=['POST'], website=True)
def object_create(self, object, **post):
if not object:
return request.render("website.404")
attachment = post.get('image')
text = post.get('text')
values = {
'text': text,
}
# If present get image data from input file
if attachment:
data_image = base64.b64encode(attachment.read())
values['image'] = data_image
request.env['object.model'].create(values)
# Redirect to the details page with new value
string_url = '/my/object/view/' + slug(object)
return werkzeug.utils.redirect(string_url)
So, now we have a sync POST that create object with text and image with a redirect to the create object.
Now, the question is:
How manage records with images or attachments update?
For simple record update i use this methods:
1) a modify button that show hidden <input> or <textarea> that will
take new values
2) an on.('change', '.class-to-monitorate') that populate an object like
point 3)
3) dataToSend = {}
It become something like:
dataToSend = {object_id: {values from input}} --> This is Good for write() inside controller
4)An ajax.jsonRpc("/my/path/for/update/value", "call", dataToSend)
The problem is that with controller type JSON and <input type="file"> i don't know how pass files.
It's possible to use a controller type="http" and send data like a <form>?
So i can receive all the changed <input type="file"/> and store them without refreshing the entire page every time.
EDIT
Here the JS that populate dataToSend object
// onChange bind that manage confirmity line values save
$(document).on("change", ".conformity-line-value", function () {
let value = $(this).val();
let name = $(this).attr('name');
let type = $(this).attr('type');
let non_conformity_line_id = Number($(this)
.closest('div.non-conformities-line')
.find("input[name='non_conformity_line_id']").val());
//If the dict for this line does not exist create it
if (!dataToSaveConformities[non_conformity_line_id]) {
dataToSaveConformities[non_conformity_line_id] = {}
}
//Add changed elements into dic to corresponding line
switch (name) {
case 'name':
dataToSaveConformities[non_conformity_line_id]['name'] = value;
if (value === '') {
$(this).addClass('error_input');
} else {
$(this).removeClass('error_input');
}
break;
case 'non_conformity_note':
dataToSaveConformities[non_conformity_line_id]['non_conformity_note'] = value;
break;
default:
break;
}
});
The class .conformity-line-value is set to all input,textarea,select,checkbox that i need to monitorate if the user change them.
Here the JS function that call controller that save data:
function save_changed_values() {
if (!isEmpty(dataToSaveConformities)) {
ajax.jsonRpc("/my/sale_worksheet_line/non_conformity/update/value", "call", dataToSaveConformities)
.then(function (data) {
//Clear data to send
for (var member in dataToSaveConformities) delete dataToSaveConformities[member];
if (data.error) {
//FIXME: check that case or manage it
$('.non-conformities-div').load(window.location + " .non-conformities-div>*", function () {
$('select.js-conformities-read-multiple').select2();
});
} else {
$('.non-conformities-div').load(window.location + " .non-conformities-div>*", function () {
$('select.js-conformities-read-multiple').select2();
});
}
});
}
}
I try to take the base64 of image from <input type="file"> and put it inside sended object (parsed as JSON)
But in the controller i receive an empty value inside **post

How to populate input fields dynamically created based on another one after an AJAX request is done?

I have this HTML code that dynamically adds barcode[] and description[] input fields to my form, using the onfocusout event, the get_barcode_data JS function below is triggered to get the barcode description, but it only works for a single barcode[] input field:
<div>
<input type="text" id="barcode[]" name="barcode[]" onfocusout="get_barcode_data(this);"/>
</div>
<div>
<textarea id="description[]" name="description[]" disabled="disabled"></textarea>
</div>
<div align="center">
</div>
The console.log(name) call displays the value I entered on any of the dynamically created barcode[] input fields and the request is successfully done but after that I don't know how to point the response to the right barcode[] and description[] fields:
function get_barcode_data(element)
{
var name = element.value;
console.log(name);
$.ajax({
method: 'POST',
url: 'include/get_barcode_data.php',
data: {
barcode: name
},
success: function(response){
if (response == 'FALSE') {
$('#barcode[]').focus();
$('#barcode[]').val('');
$('#description[]').val('');
var message = 'Invalid barcode.';
alert( message );
} else {
var res = jQuery.parseJSON(response);
$('#description').val(res.description);
}
}
});
}
Any ideas on how to solve this would be much appreciated.
Like James pointed out in the comment section, you cant have duplicate IDs in your document. You should either generate unique IDs for each element, or remove the IDs altogether.
If you generate unique IDs, you can pass the generated ID to your event handler and use it to select the correct element.
<div>
<input type="text" id="barcode_123" name="barcode[]" onfocusout="get_barcode_data(this, 'description_123');"/>
</div>
<div>
<textarea id="description_123" name="description[]" disabled="disabled"></textarea>
</div>
<div align="center">
</div>
123 should be a dynamically generated number.
And in your handler:
function get_barcode_data(element, target_id)
{
var name = element.value;
console.log(name);
$.ajax({
method: 'POST',
url: 'include/get_barcode_data.php',
data: {
barcode: name
},
success: function(response){
if (response == 'FALSE') {
$(element).focus();
$(element).val('');
$('#' + target_id).val('');
var message = 'Invalid barcode.';
alert( message );
} else {
var res = jQuery.parseJSON(response);
$('#' + target_id).val(res.description);
}
}
});
}
I would like to point out though, that this is not very good practice. Code like this get hard to maintain and breaks easily.
You would really be better off by learning a well though out framework, like Vue.js, Angular or React.

Retrieve multiple value from HTML input and store in JSON key, value[Array]

Good evening all!
I am currently working with google maps api.
The google maps asks for a json format to set directions.
Everything works fine if i make my own json object, but i would like to retrieve data from input fields and store it in the json object.
Right now i can retrieve 1 value from the input field and store it. But i woud like to retrieve multiple values. This is needed to set an direction on the maps. I need to find a way to store the multiple values in an json object as array. Correct my if i wrote some things wrong, i am not a expert :)
"key" : "Array"
See below for the example + Code
This is what i need to try to get:
A user comes to the page and sees 2 input fields, he fills in Amsterdam and Rome but he always needs Paris. So the user press the + icon. Another input field appears and he fills in Paris. when the user submits this below must be the json result from the input fields
"locatie" : ["Berlin", "Amsterdam", "Paris", "Rome"]
This is is my form:
<form onsubmit="return make_json(this);">
Locatie: <input type="text" name="locatie">
<input type="submit" name="" value="Make Trip">
</form>
My js function:
function make_json(form) {
var json = {
"locatie" : form.locatie.value
// this is what works and what i would like to retrieve from multiple input fields
//"locatie" : ["Paris", "Amsterdam"]
};
return json;
}
In the google maps api i call the function and use the json:
var jsonArray = make_json();
You can declare an array and push the values to it when the button is clicked.
// Declare location array
var locations = [];
// Button bindings
var locationButton = document.getElementById("addNewLocation");
locationButton.onclick = addNewLocation;
var displayJsonButton = document.getElementById("displayJsonObject");
displayJsonButton.onclick = displayJsonObject;
// Button functions
function addNewLocation() {
var location = document.getElementById("locationText").value;
locations.push(location);
document.getElementById("locationText").value = "";
}
function makeJsonObject() {
var json = {
location : locations
}
return json;
}
function displayJsonObject() {
var obj = makeJsonObject();
console.log(obj.location);
}
<input id="locationText" type="text" />
<button id="addNewLocation">Add</button>
<button id="displayJsonObject">Display JSON</button>
The results will be populated in the console. I have also returned the JSON object for you in the displayJsonObject() function, which you could use to pass to the API.
You can also try this, if you want to keep showing the locations entered before adding new location.
function addInput() {
var input = document.createElement('input');
input.setAttribute("type", "text");
input.setAttribute("name", "locatie[]");
inputs.appendChild(input);
}
function make_json() {
var form = document.querySelector("form");
var values = [];
var locations = form['locatie[]'];
if (locations.length) {
locations.forEach(function(input) {
values.push(input.value);
});
} else {
values.push(locations.value);
}
var json = {
"locatie": values
};
console.log(json);
return json;
}
<form>
Locatie:
<div id="inputs">
<input type="text" name="locatie[]">
</div>
<button onClick="addInput()">+</button>
<input type="submit" value="Make Trip" onClick="make_json(this)">
</form>
Note: Take care of UI. If user enters more number of inputs, UI may deform.

Categories

Resources