2

I have code like this:

jQuery("#test_btn").off("click").on("click", function () {
        jQuery.ajax({
                        type: "POST",
                        url: "/api/test/",
                        data: {
                            test: "me"
                        },
                        success: async function (response) {
                            alert("foo");
                        },
                        error: function (e) {
                            console.error(e);

                        }
                    });
        });

why the success function won't print an allert with "foo"? I nedd to use a promise function inside success... but nothing !

r1si
  • 1,136
  • 2
  • 19
  • 34

4 Answers4

3

I think your problem is that you are using an old JQuery version.

In 3.2.1 if you use an async function as feedback doesn't work

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function() {
  banner.addClass("alt");
  jQuery.ajax({
    type: "POST",
    url: "/api/test/",
    data: {
      test: "me"
    },
    success: async function(response) {
      alert("Success!");
    },
    error: async function(e) {
      alert('O no, an error! :(');
      console.error(e);

    }
  });
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="banner-message">
  <button>Send XHR request</button>
</div>

In 3.3.1 and above work perfectly

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function() {
  banner.addClass("alt");
  jQuery.ajax({
    type: "POST",
    url: "/api/test/",
    data: {
      test: "me"
    },
    success: async function(response) {
      alert("Success!");
    },
    error: async function(e) {
      alert('O no, an error! :(');
      console.error(e);

    }
  });
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <button>Send XHR request</button>
</div>
JairSnow
  • 139
  • 1
  • 3
1

jQuery don't support async on callback need to use fetch api like this

await fetch("/api/test/", {
                        method: "post",
                        body:
                            'nonce=' + encodeURIComponent("<?= generate_nonce(); ?>") +
                            "&user_id=" + encodeURIComponent("<?= $_SESSION['user_id']; ?>") +
                            "&supername=" + encodeURIComponent("<?= $_REQUEST['bot_name']; ?>") +
                            "&name=" + encodeURIComponent(valore_base) +
                            "&simple=" + encodeURIComponent("check"),
                        headers:
                            {
                                "Content-Type": "application/x-www-form-urlencoded"
                            }

                    })
                        .then(async function (response) {
//success here 
});

another solution thanks to @Kalimah Apps is declare an async function inside success callback.... the basis is that the jQuery callback can't be async

jQuery("#test_btn").off("click").on("click", function () {
jQuery.ajax({
                type: "POST",
                url: "/api/test/",
                data: {
                    test: "me"
                },
                success: function (response) {

                    async function abc(response){
                        await my_sync_func(response);
                        alert("done after async")
                    }
                    abc(response);
                },
                error: function (e) {
                    console.error(e);

                }
});

});

r1si
  • 1,136
  • 2
  • 19
  • 34
  • `async` in `.then(async function (response)` is not necessary as `.then()` will always return a `Promise`. `async function abc(response) { ... }` abc(response);` doesn't make sense either. – Andreas Nov 16 '19 at 14:26
  • `await`ing a synchronous function (`await my_sync_func`) makes no sense. – Andreas Nov 16 '19 at 14:27
  • I still don't understand the need of the OP here. Why the need of async await. To do what after? – Thanh Trung Nov 16 '19 at 14:46
  • @Andreas I found the real problem.... bug of version 3.2.1 oj jquery :( I'll post a new answer with two fiddle example. – r1si Nov 18 '19 at 11:03
0

AJAX(Asynchronous Javascript and XML) by its name it is clearly understood that the AJAX request is always asynchronous.

If you want it to be synchronous just add this,

$.ajaxSetup({
  async: false //by default it will be true
}); 

In addition to that,

The jQuery post() method sends an asynchronous http POST request to the server to submit the data to the server and get the response.

$.post('/jquery/submitData',   // url
   { myData: 'This is my data.' }, // data to be submit
   function(data, status, jqXHR) {
     // success callback
    })

Syntax:

$.post(url,[data],[callback],[type]);

Please refer this API documentation for further information. This would be helpful.

0

As the JairSnow's way, my app are using jQuery 2.2.4. And I must have following code to use jQuery 3.4.1 parallel with jQuery 2.2.4 (and I am using ASP.NET MVC):

In the index.cshtml, I added following code:

<!-- load jQuery 3.4.1 -->
    <script type="text/javascript" src="~/lib/jquery3.4.1/jquery.js" asp-append-version="true"></script>
    <script type="text/javascript">
        var jQuery_3_4_1 = $.noConflict(true);
    </script>

In javascript, I added following code:

jQuery_3_4_1.ajax({
            type: 'GET',
            url: '/Product/GetById',
            data: { id: id },
            dataType: "json",
            success: async function (item) {
                // ... my code...
                let productData;
                productData = await getFactor();
                // ... my code...
            },
            error: function (err) {
                general.notify('Error', 'error');
                console.log(err);
            }
        });
    }

And it run successfully. You can refer way to use multiple jQuery version here: Can I use multiple versions of jQuery on the same page?