Within my mongodb database, I have two Tables:
- GstState
- Store
While working on my Store
form, I encountered an issue where the JSON response was returning an undefined id
when trying to select a state based on country via an ajax call to fetch GstStates. I am struggling to pinpoint the error causing this unexpected behavior.
Below is the section of code in question:
I would greatly appreciate any assistance with resolving this issue.
JavaScript:
var countryHandle = document.querySelector('#store_country');
var stateHandle = document.querySelector('#store_gst_state_id');
countryHandle.addEventListener('change', function() {
if (countryHandle.value !== "") {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:3000/merchant_stores/find_states?
country = ' + countryHandle.value);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var states = JSON.parse(xhr.responseText);
var states1 = states.sort((a, b) =>
a.state_name.localeCompare(b.state_name))
stateHandle.innerHTML = "";
states1.forEach(function(state) {
var option = document.createElement('option');
var statename = document.createAttribute('value');
statename.value = state.id;
option.setAttributeNode(statename);
var namewithcode = state.state_name.concat(" - ", state.state_code)
var txt = document.createTextNode(namewithcode);
option.appendChild(txt);
stateHandle.appendChild(option);
});
}
}
xhr.send();
}
}, false)
HTML:
<div class="form-group">
<%= f.label :state, "State *", :class => "col-sm-2 control-label" %>
<%= f.collection_select :gst_state_id, [], :id, :state_name %>
</div>
<div class="form-group">
<%= f.label :country, "Country *", :class => "col-sm-2 control-label"
%>
<div class="col-md-10">
<%= f.select :country, options_for_select(Store::COUNTRY_CODES,
selected: @store.country),{}, class: "form-control" %>
</div>