Initializing my variable doesn’t works by first click, but by second click it works

if I enter an article number, for example 100100 and then click on the button, my array parent is empty, although it actually has to be overwritten by the method called. however, when I click the button a second time, the array is no longer empty. Why is that? I want my array to be overwritten after the first click.

my html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OMP-System</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="stückliste.js"></script>
</head>
<body>
    <h1>Stückliste</h1>
    <input type="text" id="artikelnummerStücklisteInput" placeholder="Artikelnummer">
    <button id="generateStückliste" onclick="generateStückliste()">Stückliste</button>    
</body>
</html>

my javascript:

let alleArtikelstücklisten={};
let parent={};

$(document).ready(function(){
    getAlleArtikelstücklisten();
})

function getAlleArtikelstücklisten(){
    $.ajax({
        url: "http://localhost:8080/m_stücklistenelement/all",
        type: 'GET',
        contentType: "application/json",
        success: handleData
      });
}
function handleData(data){
    alleArtikelstücklisten=data;
    console.log(alleArtikelstücklisten);
}
function getParent(artikelnmr){
    $.ajax({
        url: "http://localhost:8080/m_stücklistenelement/selectByArtikelnummerStückliste?artikelnummerStückliste="+artikelnmr,
        type: 'GET',
        contentType: "application/json",
        success: handleDataParent
      });
}
function handleDataParent(data){
    parent=data;
}

function generateStückliste(){
    var artikelnummer= $('#artikelnummerStücklisteInput').val();
    getParent(artikelnummer);
    console.log(parent);
}

Answer

Its because the console.log gets called before the getParent() function finishes. It is returning the value from the first click/call when you click it the second time.

You can pass async: false, to fix it.

$.ajax({
        url: "http://localhost:8080/m_stücklistenelement/selectByArtikelnummerStückliste?artikelnummerStückliste="+artikelnmr,
        type: 'GET',
        contentType: "application/json",
        success: handleDataParent,
        async: false
      });

Leave a Reply

Your email address will not be published. Required fields are marked *