Reputation: 71
I have Ajax JSON response data like
{"ID":["53","54"],"NAME":["Volkswagen Project ","Nevpro Project"]}
Now I want dynamic drop-down with ID as value and NAME as text. My Ajax code-
$.ajax({
url: "//<?echo $_SERVER["SERVER_NAME"];?>/services/project_data.php",
dataType: "json",
type: "POST",
//data: {lan : lan},
success: function(data){
$.each(data,function(index, element) {
var x = document.getElementById("project");
var option = document.createElement("option");
option.text = element.NAME;
option.value = element.ID;
x.add(option);
});
}
});
By this code drop-down is added but value and text shows undefined. Please some one help me to sole this issue.
Upvotes: 1
Views: 69
Reputation: 337560
The issue with your code is that data
is an object. The arrays are in the ID
and NAME
properties, so you instead need to loop through those, something like this:
var data = {
"ID": ["53", "54"],
"NAME": ["Volkswagen Project ", "Nevpro Project"]
}
// in your success handler:
var html = data.ID.map(function(id, i) {
return `<option value="${id}">${data.NAME[i]}</option>`;
});
$('#x').append(html.join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="x"></select>
Note that I used a template literal simply to keep the code tidy. You can change that to use string concatenation if you need to support older browsers.
Upvotes: 1
Reputation: 4223
Your data format should be like this, for your UI code to work:
[ {"ID":"53","NAME":"Volkswagen Project"},
{"ID":"54", "NAME": "Nevpro Project"} ]
i.e. There should be an array containing two objects. Each object with NAME
and ID
properties.
Upvotes: 0