0

it seems that I have read all about variables in JS and still can't get this piece of code working somehow. What is wrong with it?

Basically here is my piece of Jquery code:

        else if(status!="error"){
        var response="emtpy";
        console.log("Before: "+response);

        $.post("/app/admdocs.php",{chkExistAlimit:valueSelected,month:aemonthVal},function (data) {
            var resp=data.status;
            alert(data);
            console.log("Check resp: "+resp);
            var status2;

            if(resp=="ok"){
                console.log("Resp inside if: "+resp);
                response="ok"
            }

            else{
                response="no";
            }

        },"json");

        console.log("After: "+response);

    }

No matter what I do var response is not changing it's value, what is wrong with me? This is the data from console.

docs.js:453 Before: emtpy
docs.js:472 After: emtpy
docs.js:458 Check resp: ok
docs.js:462 Resp inside if: ok
Undry
  • 427
  • 2
  • 15
  • 1
    Notice how `docs.js:472 After: emtpy` is logged **before** you even have received a result from the Ajax call. `$.post` is asynchronous and the duplicate tells you all about that. This might also help with how to think about callbacks: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Nov 19 '21 at 11:45
  • Where do you see it's logged before? – Undry Nov 19 '21 at 11:45
  • 3
    The line `docs.js:472 After: emtpy` is before the line `docs.js:458 Check resp: ok`. – Felix Kling Nov 19 '21 at 11:46
  • I see. Oh thank you, thank you, thank you, you showed me where to go. – Undry Nov 19 '21 at 11:48
  • I wish the answers here would not be so complex. – Undry Nov 19 '21 at 11:55
  • 1
    Depending on what you want to do with `response`, the solution can be really simply. You can just put everything that needs to operate on `response` into a function and call the function in the `$.post` callback. – Felix Kling Nov 19 '21 at 12:21
  • This question is being discussed on [meta](https://meta.stackoverflow.com/questions/413180). – cigien Nov 19 '21 at 13:50

0 Answers0