0

I am getting json data from my php code something like this :

{2: "Robert ", 3: "Adem"}

Now i want to show it in dropdown list using jQuery I'm using the following code but 'm getting object in dropdown.

jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});
ROOT
  • 11,363
  • 5
  • 30
  • 45
user3653474
  • 3,393
  • 6
  • 49
  • 135
  • simply use `jQuery.each(response ,function(index,value){........` instead of `jQuery(response).each(function(index,value){.....` And no need for `JSON.parse` – Mohamed-Yousef Jun 03 '20 at 05:37

3 Answers3

1

Aside from doing JSON.parse(). .each() callback should be applied on Array not an Object, just convert your response object to Array using Object.values(), here is a working snippet:

let responseStr = {2:"Robert ", 3:"Adem"}; // <----- Make sure that its an object if its not then you have to do JSON.pares().
console.log(Object.values(responseStr));
jQuery(Object.values(responseStr)).each(function(index,value){
   jQuery('#name').append(jQuery('<option>').val(value).text(value));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select>
ROOT
  • 11,363
  • 5
  • 30
  • 45
0

you need to parse them using $.parseJSON() and to retrieve data.

If you want to do without parsing refer below.

How to access JSON Object name/value?

Techie
  • 44,706
  • 42
  • 157
  • 243
0

If the response coming from your PHP file is a JSON string then you will have to convert it into a javascript array then iterate it to get your option

use JSON.parse();

var options = JSON.parse(JSON.stringify(response));

jQuery.each( options, function( index, value ) {
   $('#name').append('<option value="'+index+'">'+value+'</option>');
});
Vivek Choudhary
  • 634
  • 8
  • 14