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));
});
1
  • simply use jQuery.each(response ,function(index,value){........ instead of jQuery(response).each(function(index,value){..... And no need for JSON.parse Commented Jun 3, 2020 at 5:37

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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>');
});

6 Comments

but now i'm getting: Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse
Give it a try now.
now it not throwing any error but a single object in dropdown is shown, when i console options i get {2: "Rod ", 3: "Adem"}
Just try to append option with your old approach or append the HTML directly.
same result is there
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.