Populate SELECT options with Ajax.

This is a JavaScript tutorial on how to populate a SELECT element’s options with an Ajax request. In this tutorial, I will be using the JQuery library.

In this example, I will be sending an Ajax request to a PHP script, which will return a list of car models in a JSON format. After that, I will take the returned JSON data and append each array element to the SELECT dropdown.

Our PHP script.

I’ve purposely kept this short and simple, as your script will probably be completely different. In the example below, I’ve created a PHP array of car models and printed it out in a JSON format:

In your case, you will probably be selecting data from MySQL. You may also be doing a search based on form elements that the user has already filled in or changed.

Our Select element.

Once again, I have kept this example very simple:

As you can see, we created a SELECT element with the ID “car_models“. We also added a default “loading” option, just to let the user know that they may have to wait a few seconds before they can select anything.

Our JavaScript / jQuery.

Now, let’s take a look at the JavaScript code that will send an Ajax request to our PHP script before populating the above SELECT element:

In the example above, we wrapped our request inside the $(document).ready function. As a result, our Ajax request will be executed as soon as the page has loaded and the DOM is ready. You may want to change this to suit your scenario.

For example: You might want to change the SELECT element after another SELECT element has been changed. In that case, you would modify the code above and wrap it inside the onchange event handler.

Inside the success handler of our AJAX request, we used the $.each function to loop through each element in the JSON array that our PHP script returned. We then converted each car model into an Option element before appending it to our SELECT dropdown.

Finally, after our loop finished, we changed the text of the default loading option so that the user realizes that they can now use the element.

This code will obviously need to be modified to suit your own needs and setup. If you are having issues understanding how to do that, then you should probably check out some of these beginner guides:

Facebook Comments