1

I have the following PHP file that I will call using my $.ajax() in my JS:

<?php
    header('Content-Type: application/json');
    echo json_encode(array('One' => 'Test'));
?>

And I have the following code in my JS:

<script type = "text/javascript">
    let changeValue;
    $('#someElementID').click(function() {
        $.ajax({
            type: 'POST',
            url : 'phpfile.php',
            dataType : 'json',
            success: function(obj, textStatus) {
                changeValue = obj.One;
            }
        });

        $('#toBeChangedElementValue').text(changeValue);
    }
</script>

Problem is: the changeValue variable only gets its value after my $('#toBeChangedElementValue').text() has been executed. How does it work? How do I fix this? I had to place $('#toBeChangedElementValue').text(changeValue) in my success callback instead to make it work. Why didn't my changeValue get updated first before that final .text() happened?

Richard
  • 7,037
  • 2
  • 23
  • 76
  • Put `$('#toBeChangedElementValue').text(obj.One);` inside the success callback? There are other ways to do this (with `await` for instance), but this is the most "traditional" way to deal with async code. – Jeto Feb 16 '19 at 08:27
  • @Jeto Yeah, I did figure that out. I'm just curious why doesn't my `changeValue` value assignment happen first. – Richard Feb 16 '19 at 08:31
  • Because [`$.ajax`](http://api.jquery.com/jquery.ajax/) is asynchronous. Code following it will execute right away, and the callbacks will be called only when the result/error is ready. You can use `const result = await $.ajax(...)` as an alternative (modern JS, so might not be compatible with older browsers if you don't use [Babel](https://babeljs.io/)). – Jeto Feb 16 '19 at 08:35
  • @Jeto I see. Thank you. Can I ask you some other questions that are not related to this current question? – Richard Feb 16 '19 at 08:37
  • Please create other questions instead. I'll vote this one as duplicate as I finally found the related question I was thinking about. – Jeto Feb 16 '19 at 08:41
  • @Jeto The 90-min restriction is pretty bothersome, though. – Richard Feb 16 '19 at 08:46
  • @WealthyPlayer — Spend the time researching the problem instead. – Quentin Feb 16 '19 at 08:50

0 Answers0