Should I use AJAX for this?

I have this form


and am trying to create an effect so if you select a country, the state select box is filtered.
So now, when I select a Country from

<form action="add_country.php" method="POST" name="country_form">
<select class="form-control" id="Country" name="Country" onchange="this.form.submit()">
<option value=1>Test Country 1</option>
<option value=2>Test Country 2</option>
<option value=3>Test Country 3</option>
<option value=4>Test Country 4</option>
</select>	
</form>

I get

Array
(
    [Country] => 2
)

4: Test State 4
5: Test State 5
6: Test State 6

so the form is handled correctly.
I want to submit the form so the whole page doesnt need a refresh (only the state select bex.
I gather AJAX is good.
Do I just need

<script>
	const xhr = new XMLHttpRequest();

	xhr.onload = () => {
	  const serverResponse = document.getElementById('Country');
	  serverResponse.value = this.responseText;
	};

	const requestData = `id=${serverResponse.value};

	xhr.open('post', 'add_country.php');
	xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	xhr.send(requestData);       
}
</script>

It’s recommended these days that the Fetch() API is used for ease of use and reliability instead of AJAX.

2 Likes

this
https://www.youtube.com/watch?v=cuEtnrL9-H0

Yes, that’s a suitable resource by which to learn more about it.

I gather I need to understand AJAX, then move on to that (My Coworker said thats the best way). So Im stuck, have a form, but when its submitted, to

<?php echo '
';print_r($_POST);echo '
'; ?>

why does the console show an empty array?
Heres the script

<script>
document.getElementById('Country').addEventListener('change',postCountry);
  
    function postCountry(e){
      e.preventDefault();


      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'state_options.php', true);
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

      xhr.onload = function(){
        console.log(this.responseText);
      }

      xhr.send();
    }

</script>


Oh, I had to use

xhr.send("Country="+document.getElementById('Country').value);

To answer your question: No, use the fetch API.
It is far more reliable and returns a promise which results in much more understandable code.
More understandable code makes for easier debugging.

2 Likes

Promise is one reason to use fetch. Another is simplified interface to communicate with an external http api.

No hard feelings, but please then get your coworker to teach you AJAX instead. We Many of us would rather not delve further into that mess, now that we have much better ways of doing things.

1 Like

I accept people who want to understand the basics and not use frameworks without any knowledge of what is happening.

Some links for you.

If you want some background on the old way of doing things.

And moving on to the better way of doing things

More in depth

2 Likes

I recommend not using Ajax for this. For those countries which have states, provinces, territories etc simply include the options with the web page. The amount of data to do this will be small, even in comparison with the data required for a fairly small photo image. There are two ways to do this:

  1. Include <select> elements for each country which has states etc but do not display them initially. Display the appropriate <select> element (if any) when a country has been selected.

  2. In JavaScript have arrays for the states etc in each country that has states etc. When a country has been selected, transfer the appropriate array values to a <select> element.

I demonstrate the first method here:

It seem inadvisable to have a <select> element for ‘City’ especially as very many people do not live in cities or have a city as part of their postal address.

So you would prefer to load all unneeded countries and regions data with the page even if it is never used?

I don’t like this approach.

Definitely yes!

If you use my second method with an array of region names for each country, then for USA the array declaration for 50 states would take only 620 bytes (only 155 bytes if abbreviations are used). In comparison, the OP’s tiny avatar at the top of this thread is 2722 bytes. Other countries have far fewer regions and some countries such as UK, Germany and France do not include regions in postal addresses.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.