What is the process for adding JSON data to a dropdown menu using PHP AJAX?

I am trying to populate a select html element with data from a list of JSON results. Here is the code I have attempted:

JSON output: jquery loop on Json data using $.each

{"Eua":"Eua","Ha'apai":"Ha'apai","Niuas":"Niuas","Tongatapu":"Tongatapu","Vava'u":"Vava'u"}

 success: function(result){
                    
                    console.log(data);
                    var data = jQuery.parseJSON(result);
                    jQuery.each(data,function(key, value)
                {   //jQuery("#state").html();
                    console.log(key);
                    jQuery("#state").html('<option>'+value+'</option>');
                })

Answer №1

By utilizing the following code snippet:

jQuery("#state").html(...)

you will overwrite the existing option with a new one, ultimately displaying only the last Json value.

If you utilize:

jQuery("#state").append(...)

Instead, this code will add an additional option to the select dropdown without removing any of the previous options.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Some suggestions for updating two div elements using only one Ajax response

My website features a signin() button that I want to enhance with ajax functionality. When the button is clicked, I need it to update two divs: one displaying a personalized welcome message, and the other showcasing a statistics table in a different locati ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

Guide to running a NextJS app alongside an Express server backend on the same localhost port

I'm working on hosting my NextJS app, which is built with React, on the same localhost port as my express api-server backend. Within my express server API settings, I have configured my API server to listen on: http://localhost:3000/graphql How can ...

Utilize PHP to populate grouped tables and filter them using jQuery through AJAX with JSON

There are two PHP files in play here. The first one, fetch.php, creates a filtered array (filtered from leagueboxes.php) and then sends it back to leagueboxes.php via Ajax JSON. fetch.php <?php include_once 'dbconfig.php'; if(isset($_GET[ ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

Ensure that a synchronous action is performed prior to each Backbone HTTP request

For each authenticated request (GET, POST, etc) in my Backbone/Marionette application, it is necessary to include an accessToken. The accessToken and expireDate are stored in the localStorage. To verify if the accessToken has expired, I utilize the metho ...

Error in Jquery Ajax due to an unexpected token ':' being caught

My spring MVC application is experiencing an issue when using jQuery AJAX to send data to the server from my HTML page. The error message indicates a problem with dataType: 'json', specifically pointing out the unexpected symbol :. $(document).r ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

How to target only the parent div that was clicked using jQuery, excluding any

I have attempted to solve this issue multiple times, trying everything I could find on Google and stack overflow without success. At times I am getting the span element and other times the div - what could be causing this inconsistency? $(".bind-key"). ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Discovering the number of intervals running at any given time within the console - JavaScript

I'm having trouble determining if a setInterval() is active or has been cleared. I set up an interval and store it in a variable: interval = setInterval('rotate()',3000); When a specific element is clicked, I stop the interval, wait 10 sec ...

In react-native, both the parent and child components are rendered at the same time

One of my components, the parent one, goes through an array of chapters and for each item found, renders a child component called 'ExercisesList' and passes an array of exercises to it. class ExercisesScreen extends Component { displaySelected ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

AJAX and Python conflict - The requested resource is missing the 'Access-Control-Allow-Origin' header

I am currently developing a unique JavaScript library that has the capability to communicate with a basic Python web server using AJAX. Below is the snippet for the web server class: class WebHandler(http.server.BaseHTTPRequestHandler): def parse_PO ...

The chat text will automatically scroll down, displaying information loaded from the database

Is there a way to ensure that chat text always remains scrolled to the bottom of the chat? I have tried multiple tutorials and examples from Stack Overflow, but none seem to work for me. Currently, my chat text overflows the textarea when there are too m ...

Tips on displaying substitute text in Angular when an Iframe fails to load the content located at the src

Currently, I am working on an Angular 12 application and have a requirement to fetch content from an external site and display it within a modal popup. To achieve this, I am using the <iframe src="url"> tag to retrieve the content from a se ...