1

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>
Bill Tate
  • 31
  • 2
  • Remove `contentType: "application/json",` - you're not sending json (or change `data:` so it does send json) – freedomn-m Sep 27 '22 at 15:16
  • Related answers can also be found [here](https://stackoverflow.com/a/73761724/17865804) and [here](https://stackoverflow.com/a/73096718/17865804.) – Chris Sep 27 '22 at 16:13
  • Thanks for the assist. I'll definitely check these out. – Bill Tate Sep 27 '22 at 16:26

1 Answers1

1

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);
    });
    
}
Bill Tate
  • 31
  • 2