skip to Main Content

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


  1. 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:

    $.each(data.director, function(i, term) {
        $('#acf-field_5dc7e03cd489d').append(new Option(term.text, term.id, true, true)).trigger('change');
    });
    

    with the data you posted, it will run twice. In the first iteration, i will take the value id and term will be the array [83,84,85]. In the second iteration , i will take the value text and term will be the array ["Matsuyama Hiroaki","Aizawa Hideyuki","Mihashi Toshiyuki"].

    If you want to append options based on both id and text you can do something like:

    data.director.id.forEach(function(id, index) {
        $('#acf-field_5dc7e03cd489d').append(new Option(data.director.text[index], id, true, true)).trigger('change');
    }); 
    
    Login or Signup to reply.
  2. ‘data.director’ is not an array but ‘data.director.id’ is so this is where the loop needs to happen. Below correction will work 🙂

    $.each(data.director.id, function(i, term) {
      $('#acf-field_5dc7e03cd489d').append(new Option(data.director.text[i], term, true, true)).trigger('change');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search