Ajax with multidimensional JSON type feedback

Asked

Viewed 449 times

2

Save, I bugged here trying to make ajax bring me some data from a JSON and I need a lesson/help to understand how I pull the values of an object array(I think this is it rsrs). I have the following code below, it’s a bit confusing, but my goal is to do the following:

  • Field "areaatu_02" was selected?
  • yes: Then returns "select" from html with the values of "posses_title" that are in JSON

only that I never worked with a more complex structure of JSON, stirred with a simpler one ex: { "name": "Rafael Eduardo"}

Now I’m coming across array inside array and it’s bugging my head a lot...

Got very confused my doubt? follows below the code I tried to create:

json.php

 $obj = ('{
    "area_atuacao": [{
        "areaatu_02": [{
            "portador_titulo": [
                "AMB",
                "RESIDÊNCIA MÉDICA"
                ],
            "possui_titulo": [
                "MEDICINA PREVENTIVA E SOCIAL",
                "ADMINISTRACAO EM SAUDE" 
            ]
            }],
        "areaatu_04": [{
            "portador_titulo": [
                "AMB",
                "RESIDÊNCIA MÉDICA"
                ],
            "possui_titulo": [
            "ALERGIA E IMUNOLOGIA",
            "PEDIATRIA"
            ]
            }],
        "areaatu_07": [{
            "portador_titulo": [
                "AMB",
                "RESIDÊNCIA MÉDICA"
                ],
            "possui_titulo": [
            "ANGIOLOGIA",
            "CIRURGIA VASCULAR",
            "RADIOLOGIA"
            ]
            }]
    }]

}
');
// converto em um Array
    $myARRAY = json_decode($obj);
//coloco na tela
    echo json_encode($myARRAY);
    ?>

php test.

        <select name="AREA_ATUACAO" class="form-control" id="areaAtu" onchange="areaAtuFun()">
                            <option value="erro" disabled="disabled" selected>-- Selecione uma opção --</option>
                            <option value="areaatu_01">ACUPUNTURA</option>
                            <option value="areaatu_02">ADMINISTRAÇÃO EM SAÚDE</option><!-- TEM REGRA -->
                            <option value="areaatu_03">ALERGIA E IMUNOLOGIA</option>
                            <option value="areaatu_04">ALERGIA E IMUNOLOGIA PEDIÁTRICA</option><!-- TEM REGRA -->
                            <option value="areaatu_05">ANESTESIOLOGIA</option>
            </select>
<div class='form-group col-md-4'>
<label for='PossueAreaAtu'>Portador do título de:</label>
<select name='PORTADOR_TITULO' class='form-control' id='PossueAreaAtu'>
<option value='erro' disabled='disabled' selected>-- Selecione uma opção --</option>
<span id="areaAtu_here"></span>
</select></div>


   <script>         
    function areaAtuFun() {

        var opFormValue = $('#areaAtu').val();
        var opFormUrl = "json.php?data=area_atuacao."+ opFormValue;

        $.ajax({
            dataType: "json",
            url: opFormUrl,
            method: "GET", 
            data: data,
            success: function(retorno){
                if (retorno.count != 0) {
                        $(retorno.area_atuacao).appendTo("#areaAtu_here")
                    }else{
                        alert("Deu ruim.")
                    }
            },
            error: function(){
                alert("Falha de conexão, tente novamente.")
            }
        })
                    var opForm = document.getElementById("areaAtu").value;
                    document.getElementById("areaAtu_here").innerHTML = "<option >"+ opForm +"</option>";
     }

  • What do you want to put inside .appendTo("#areaAtu_here")?

  • @Sergio a <option> with the value returned by ajax... O opForm to be more precise.

  • But ajax returns an object with an array, you want an option for each element of the array? with what content? can you exemplify this(s) option(s)?

  • @Sergio imagine that I selected the "areaatu_04" in my select id="areaAtu", I want in the option it appears the options of area_atuacao.areaatu_04.possui_titulo which is in JSON, more precisely: <option>ALERGIA E IMUNOLOGIA</option> and <option>ADMINISTRACAO EM SAUDE</option>

  • But ADMINISTRACAO EM SAUDE is from areaatu_02... what is the logic of it appearing? wouldn’t it be PEDIATRIA?

  • @Sergio, is wrong, is not areaatu_04 was the same 2, I wrote wrong rsrs sorry... but the logic is this, show the options of what I select

  • Okay, and the old options disappear right?

  • that’s right, correct!

  • Okay, and this JSON has to have that format or can I suggest another?

  • @Sergio can do it, man, mine’s a bit fucked up

Show 6 more comments

2 answers

1


Here is a solution, which involves changing the structure of JSON (since you said it was possible). That way it gets simpler if you don’t need to complicate it better.

Structure of the JSON:

{
    "areaatu_02": {
        "portador_titulo": [
            "AMB",
            "RESIDÊNCIA MÉDICA"
        ],
        "possui_titulo": [
            "MEDICINA PREVENTIVA E SOCIAL",
            "ADMINISTRACAO EM SAUDE"
        ]
    },
    "areaatu_04": {
        "portador_titulo": [
            "AMB",
            "RESIDÊNCIA MÉDICA"
        ],
        "possui_titulo": [
            "ALERGIA E IMUNOLOGIA",
            "PEDIATRIA"
        ]
    },
    "areaatu_07": {
        "portador_titulo": [
            "AMB",
            "RESIDÊNCIA MÉDICA"
        ],
        "possui_titulo": [
            "ANGIOLOGIA",
            "CIRURGIA VASCULAR",
            "RADIOLOGIA"
        ]
    }
}

jQuery:

function areaAtuFun() {

    var opFormValue = $('#areaAtu').val();
    var tituloSelect = $('#PossueAreaAtu');
    var opFormUrl = "json.php?data=area_atuacao." + opFormValue;

    $.ajax({
        dataType: "json",
        url: opFormUrl,
        method: "GET",
        success: function(retorno) {
            var valores = retorno[opFormValue].possui_titulo;
            if (valores.length == 0) return alert('Houve um erro com os dados! 0');
            $('#PossueAreaAtu option').remove(); // apagar as options existentes
            valores.forEach(function(string) {
                $('<option/>', {
                    value: string,
                    html: string
                }).appendTo(tituloSelect);
            });
        },
        error: function() {
            alert("Falha de conexão, tente novamente. 1")
        }
    })
}
  • Much simpler than I thought! , thank you very much!

0

To transform JSON into Array, you need to indicate the true within the json_decode

Thus remaining:

$myARRAY = json_decode($obj, true);

And to get the data in PHP just try:

$myARRAY['area_atuacao']['areaatu_04']['...'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.