I’ve seen similar posts for this issue, but haven’t found a solution that worked for me.
My Json which is valid in Jsonlint:
{
"genre": {
"id": 44,
"text": "Mystery"
},
"status": "11 episodes",
"director": {
"id": [
83,
84,
85
],
"text": [
"Matsuyama Hiroaki",
"Aizawa Hideyuki",
"Mihashi Toshiyuki"
]
}
}
My ajax call:
$.ajax({
url: link, //link to php file
type: "POST",
data: postForm,
dataType : 'json',
success: function (data) {
console.log(data);
if(data !== "fail"){
$.each(data.director, function(i, term) {
$('#acf-field_5dc7e03cd489d').append(new Option(term.text, term.id, true, true)).trigger('change');
}); // Append options to field in post editor
$("#get_all").val("Submit");
$("#get_all").removeAttr('disabled');
}else{
alert("fail");
$("#get_all").val("Submit");
$("#get_all").removeAttr('disabled');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$("#get_all").val("Submit");
$("#get_all").removeAttr('disabled');
}
});
It is creating the options but blank, the console show undefined.
2
Answers
When you call
$.each
on an object, the first parameter of the callback is the property name and the second one its value. So, when you do:with the data you posted, it will run twice. In the first iteration,
i
will take the valueid
andterm
will be the array[83,84,85]
. In the second iteration ,i
will take the valuetext
andterm
will be the array["Matsuyama Hiroaki","Aizawa Hideyuki","Mihashi Toshiyuki"]
.If you want to append options based on both
id
andtext
you can do something like:‘data.director’ is not an array but ‘data.director.id’ is so this is where the loop needs to happen. Below correction will work 🙂