0
I have an ajax function that looks for the code of all companies and goes in the other ajax function looking for employees.
So that the page does not stop when doing this search I am using the attribute async: true
, only that while doing so, I cannot get the data back on the page even working using the console.log()
Follow my code to be analyzed
$( document ).ready( function(){
empresas()
} )
let empresasArr = {
"empresa":[
{
"nome": "Digiboard",
"id": 1
},
{
"nome": "HAM",
"id": 2
}
]
}
let dadosArr = {
"dados": [
{"nome": "Carlos", "empresa": 1},
{"nome": "Vicente", "empresa": 2},
{"nome": "Maiza", "empresa": 2},
{"nome": "Charles", "empresa": 1},
{"nome": "Michel", "empresa": 2}
]
}
function empresas(){
$.ajax({
url: 'https://api.myjson.com/bins/b0c22',
type: 'post',
dataType: 'json',
async: false,
}).done( function( d ){
var retorno = "";
let string = ""
console.log( d )
$.each( d.empresa, function(i, j){
console.log( j.nome )
retorno = fnNomes( j.id, function( retorno ){
//console.log( retorno )
string =+ retorno
} )
})
console.log( string )
$('.retorno').append(string)
})
}
function fnNomes( id, cb ){
let nomes = "";
$.ajax({
url: 'https://api.myjson.com/bins/1cksbu',
type: 'POST',
async: true,
dataType: 'json',
data: { empresa : id }
}).done( function( d ){
console.log( d )
$.each( d.dados, function(i, j ){
if( j.empresa == id ){
nomes += j.nome+"<br>"
}
})
cb( nomes )
} )
// console.log(nomes);
return nomes
}
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<div class="retorno"></div>
the file Company.json
{
"empresa":[
{
"nome": "Digiboard",
"id": 1
},
{
"nome": "HAM",
"id": 2
}
]
}
The aqruivo json data.
"dados": [
{"nome": "Carlos", "empresa": 1},
{"nome": "Vicente", "empresa": 2},
{"nome": "Maiza", "empresa": 2},
{"nome": "Charles", "empresa": 1},
{"nome": "Michel", "empresa": 2}
]
I heard about such deferred and promised, would not solve the problem, but I still do not understand how to use
On the second I would like to send the post
– adventistaam