Save, I buggy here trying to get ajax to fetch data from a JSON and I need a class / help to understand how I pull the values from an array of objects (I think that's it). I have the following code, it's kind of confusing, but my goal is to do the following:
- Field "areaatu_02" selected?
- Yes: Then it returns as "select" from the html with the values of the "own_title" that are in JSON
But I've never worked with a more complex JSON structure, I've been working with a few more simple ones: {"name": "Rafael Eduardo"}
Now I'm encountering an array inside the array and this is bugging my head a lot ...
Was my question too confusing? here is 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);
?>
test.php
<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>";
}