Gathering every individual value from the array of ajax objects

controller

public function ajaxData(){

            $country_id=$this->input->post('country_id',true);

            $this->load->model('country_m');
            $data['states']=$this->country_m->getStates($country_id);

            echo json_encode($data);
            $this->load->view('onlineappointment.tpl',$data,TRUE);
  }

ajax

$(document).ready(function(){

    $('#country').on('change',function(){
        var countryID = $(this).val();
        // alert(countryID);
        if(countryID){
            $.ajax({
                type:'POST',
                url:'http://localhost/new_jivaamri/index.php/OnlineAppointment123/ajaxData',
                data:'country_id='+countryID,
                success:function(html){
                       console.log(html);
                       console.log(typeof html);

                        var obj2 = JSON.parse(html);

                       $('#state').html(html);

                    $('#city').html('<option value="">Select state first</option>'); 

                }
            }); 
        }else{
            $('#state').html('<option value="">Select country first</option>');
            $('#city').html('<option value="">Select state first</option>'); 
            $('#address').html('<option value="">Select state first</option>'); 

        }
    });

I am receiving the ajax response output as shown below:

{"states":[{"state_id":"45","state_name":" Kabul","country_id":"1","active":"1"},{"state_id":"46","state_name":"Kandahar","country_id":"1","active":"1"},{"state_id":"47","state_name":"Herat","country_id":"1","active":"1"},{"state_id":"48","state_name":"Mazar-i-Sharif","country_id":"1","active":"1"},{"state_id":"49","state_name":"Kunduz","country_id":"1","active":"1"},{"state_id":"50","state_name":"Taloqan","country_id":"1","active":"1"},{"state_id":"51","state_name":"Jalalabad","country_id":"1","active":"1"},{"state_id":"52","state_name":"Puli Khumri","country_id":"1","active":"1"}]}

However, I am unsure how to extract the state names from the response.

Answer №1

Extract response:

JSON.parse()

Retrieve state name:

parsed.states[index].state_name

Update: How to display an option in the select menu.

HTML:

<select id="state_select"></select>

JAVASCRIPT

var option = '';
for (var i = parsed.states.length - 1; i >= 0; i--) {
    options += "<option value=\""+parsed.states[i].state_name+"\">"+parsed.states[i].state_name+"</option>";
}

document.getElementById('state_select').innerHTML = options;

Working demonstration

var json = '{"states":[{"state_id":"45","state_name":" Kabul","country_id":"1","active":"1"},{"state_id":"46","state_name":"Kandahar","country_id":"1","active":"1"},{"state_id":"47","state_name":"Herat","country_id":"1","active":"1"},{"state_id":"48","state_name":"Mazar-i-Sharif","country_id":"1","active":"1"},{"state_id":"49","state_name":"Kunduz","country_id":"1","active":"1"},{"state_id":"50","state_name":"Taloqan","country_id":"1","active":"1"},{"state_id":"51","state_name":"Jalalabad","country_id":"1","active":"1"},{"state_id":"52","state_name":"Puli Khumri","country_id":"1","active":"1"}]}';

var parsed = JSON.parse(json);

var options = '';
for (var i = parsed.states.length - 1; i >= 0; i--) {
    options += "<option value=\""+parsed.states[i].state_name+"\">"+parsed.states[i].state_name+"</option>";
}

document.getElementById('state_select').innerHTML = options;
<select id="state_select"></select>

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

Configuring the TradingView widget with NextJS Script

Struggling with transferring an article on my website from Jekyll to NextJS, I'm facing a roadblock in passing widget configuration to the built-in Script component. The widget doesn't display as it should. Below is the snippet of code causing th ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...

Error encountered while attempting to import external JSON data into SurveyJS

This Codepen example showcases SurveyJS using a simple JSON structure: var json = { "questions": [{ "type": "text", "title": "Test question 1", "name": "Test question" }, { "type": "comme ...

Successful AJAX value transfer with no corresponding output

I have implemented a functionality where a user types in a textarea, presses tab, and then an Ajax call retrieves data to populate a select box based on the input from the textarea. <body> <textarea id='test' name="test"></te ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...

Using Javascript to create a radio button group

Is there a way to trigger an alert message when all radio buttons are checked as 'no'? I currently am only able to check each radio button individually. //The method I currently know $('#attraction1').change( function(){ if ($(this ...

In the Sandbox, element.firstChild functions properly, but it does not work in the IDE

Encountered an issue that has me puzzled. To give you some context, I attempted to create a native draggable slider using React and positioned it in the center of the screen, specifically within my Codesandbox file. The code snippet I utilized is as follow ...

I am currently facing a challenge in animating my ng-show/ng-hide animation

This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...

FullCalendar Not Responding to JSON Parsing

Here is how my FullCalendar jQuery code is set up: $(document).ready(function () { $('#calendar').fullCalendar({ events: { url: '/admin/index.php', type: 'GET', data: { m: '1&apo ...

Unlock the power of Redux: Crafting specialized selectors with parameters

I am currently working with a state that contains a map array of data. I find myself needing to select a single object from this array. To achieve this, I can retrieve the entire array in my component using: function mapStateToProps (state) { return { ...

The deployment of my Node application on Heroku is causing an error message: node-waf is not

I've been trying to deploy my Node.js application on Heroku by linking it to my Github repository and deploying the master branch. Despite experimenting with various methods, I keep encountering the same error every time. You can view the detailed b ...

What is the best way to hear an event emitted by a component?

I am trying to listen for an event in Chrome DevTools Vue, but I'm not sure how to target it. For a Root event, I typically use: this.$root.$on("note_id", (note_id) => (this.note_id = note_id)); But how do I address an event that origina ...

Test a JavaScript function within an Angular service using the Jasmine framework

I need to write a unit test for a JavaScript function within an Angular service using Jasmine. Here is the Angular service: angular.module("app.services").service("validationService", ["$q", function ($q) { this.validate = function (filter): ng. ...

Avoid triggering a keydown event if certain div elements have been clicked

When the user presses the space bar, my script is set up to perform certain actions, such as stopping an audio player: $('html').keydown(function(e){ if(e.keyCode == 32){ // Stop the audio player } } However, an issue arises when a ...

ESLint warning: Potentially risky assignment of an undetermined data type and hazardous invocation of an undetermined data type value

Review this test code: import { isHtmlLinkDescriptor } from '@remix-run/react/links' import invariant from 'tiny-invariant' import { links } from '~/root' it('should return a rel=stylesheet', () => { const resp ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Steps to integrating an interface with several anonymous functions in typescript

I'm currently working on implementing the interface outlined below in typescript interface A{ (message: string, callback: CustomCallBackFunction): void; (message: string, meta: any, callback: CustomCallBackFunction): void; (message: string, ...m ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

The onChange event seems to be failing to activate during a jQuery / Ajax form submission

Differences in Form Submission Methods The onChange event functions correctly with the traditional Type and Action method in both Firefox and Chrome. <form name="frmname" action="./add_p.php" method="POST"> <div> <select name=" ...