I'm using two html select form elements - both with the multiple attribute set. I am attempting to send a $.ajax post request to a FastAPI post method. This api method works for both POSTMAN and using Fastapi DOCs interface. The following is the fastapi snippet and the client side jquery ajax method I'm sending. I'm getting a 422 HTTP Response back from the server and I suspect it has something to do with my formatting things. Any help would be greatly appreciated.
The Fastapi side of things
class FilterModel(BaseModel):
state_abbrev: list[str] = []
card_type: list[str]= []
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
@router.post('/filter')
async def filter_cards(filterModel: FilterModel, db: Session=Depends(get_db)):
state_abbrev = filterModel.state_abbrev
card_type = filterModel.card_type
if state_abbrev:
cards = db.query(models.Cards).filter(models.Cards.state_abbrev.in_(state_abbrev))
if biz_type:
cards = cards.filter(models.Cards.card_type.in_(card_type))
cards = cards.all()
return {"cards":cards}
On the client side
<script>
const form = document.getElementById('map-filter-form');
let states;
let card_types;
$(document).ready(function(){
form.addEventListener('submit', (e) => {
e.preventDefault();
states = JSON.stringify( $('#state_abbrev').val());
card_types = JSON.stringify($('#card_type').val());
data = {"state_abbrev": states, "card_type": card_types};
$.ajax({
url: "http://localhost:8000/mapview/filter",
type: "post",
data: data,
contentType: "application/json",
success: function(rslts) {console.log(rslts)}
});
});
});
</script>
Thanks for the replies. Chris' response gave me what I needed to make this work with some modifications. Perhaps not as succinct as others but I think it's clear what's going on. Thanks again to the responders...
function submit_form(){
const form = document.getElementById('map-filter-form');
let state_abbrev = document.getElementById('state_abbrev');
let card_type = document.getElementById('card_type');
let states = [...state_abbrev.selectedOptions]
.map(option => option.value);
let card_types = [...card_type.selectedOptions]
.map(option => option.value);
data = {"state_abbrev": states, card_type: card_types};
body = JSON.stringify(data);
fetch("/mapview/filter", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body:body
})
.then(response=> response.text())
.then(data => {
console.log(data);
})
.catch(error =>{
console.log(error);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.