formsapinested-formsjquery-ajax

A form having fields for personal info And also states, Cities fetching data from api... How to Make them work all togather without submitting form


Context I have created a form which is taking user data like their name, phone no, address...

For the address I'm using an api that is fetching states to a drop-down and also the cities after selecting a particular state...

I've done the state part because it doesn't require a submit request.

Now, the problem is that... For fetching cities I tried jQuery and ajax but that requires a post request and I have other details for the form too so how do I make the cities drop down fetch the data of selected state without submitting the form (POST REQUEST)? Since nested form doesn't work in html it's difficult for me to find the solution..

Please help me on this..


Solution

  • You should make the fetch/ api call for the cities data on an event triggered by user over and the UI element which in your case should be the onChange event of the dropdown/select of the states.

    const stateSelector = document.querySelector('.stateSelect');
    
    stateSelector.addEventListener('change', function(e) {
        getCitiesForState(e.target.value);
    });
    
    function getCitiesForState(state) {
        fetch(`http://exapleapitogetallcitiesinstate/${state}`, {
            "method": "GET",
        })
        .then(response => response.json())
        .then(data => {
            console.log("cities data", data)
            // show cities dropdown, populate options in the select with the data
        })
        .catch(err => {
          console.log(err)
        });
    }
    

    Instead of vanilla js you can use jquery

    for event handling https://api.jquery.com/change/#example-0

    and fetching data with https://api.jquery.com/jquery.get/