0

The following function checks errors in my form. One of the fields must be validated in the server. However, when I post the field the function continue and return from the function before I get answer from the server. I must get the result from the server before returning from the function. This is my code:

function checkErrors()
    {
        var ErrorMsg = "";          
        var buyerPublicKey = document.getElementById("BuyerAddressTxt").value;
        if (buyerPublicKey == "")
        {
            ErrorMsg = ErrorMsg+"Please Insert buyer Public Key.<br>";         
        } 

        var dealPrice = document.getElementById("PriceEthTxt").value;
        if (dealPrice == "")
        {
            ErrorMsg = ErrorMsg+"Please Insert buyer price.<br>";     
        }
        var timeTobeOpen = document.getElementById("TimeSelector").value;
        if (timeTobeOpen == "Deafult")
        {
            ErrorMsg = ErrorMsg + "Please Insert time.<br>";
        }
        var url = "/CreateContract/CheckBuyerPublicKeyLegality";
        $.post(url, { BuyerPublicKey: buyerPublicKey }, function (data) //Here the problem begins
        {
           console.log("Buyer balance"+data)
           if (data == -1)
           {
            ErrorMsg = ErrorMsg + "Buyer Public Key is illegal.<br>";//
            console.log("1-->" +ErrorMsg );
           }

         });
        console.log("2-->" +ErrorMsg );
        return ErrorMsg;
    }

As you can see, I get the 2--> ErrorMessage before the 1--> ErrorMessage , which means the the posting operates asynchronously, while I need it to be synchronously.

What can I do here to change it?

chandu komati
  • 795
  • 1
  • 5
  • 21
חיים חדד
  • 512
  • 5
  • 17
  • 1
    I tried to work with await, and while loop. None of them worked – חיים חדד Dec 09 '19 at 06:09
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Dec 09 '19 at 06:10
  • Why can't you just let the submission fail on the server validation, inform the client and ask them to re-try? – Teemu Dec 09 '19 at 06:13
  • You can try an `async` function, but that will only make your code *look like it would've been synchronous*, but it won't prevent the function from returning (due to asynchrony). A `while` loop won't work as well, because of how the event loop work, it will block all other JS code, including the AJAX's callback. So, there's no good way to synchronize an asynchronous function. Asynchrony is hard. – FZs Dec 09 '19 at 06:16
  • *"I tried to work with await, and while loop. None of them worked"* You need to change your expectation. You can not make ajax requests synchronous. You need to deal with their async nature in the code that calls `checkErrors()` – Thomas Dec 09 '19 at 06:47

1 Answers1

0

Use async. By default async is set to be true, change it to false. Like this,

function checkErrors(){
var ErrorMsg = "";          
var buyerPublicKey = document.getElementById("BuyerAddressTxt").value;
if (buyerPublicKey == "")
{
    ErrorMsg = ErrorMsg+"Please Insert buyer Public Key.<br>";         
} 

var dealPrice = document.getElementById("PriceEthTxt").value;
if (dealPrice == "")
{
    ErrorMsg = ErrorMsg+"Please Insert buyer price.<br>";     
}
var timeTobeOpen = document.getElementById("TimeSelector").value;
if (timeTobeOpen == "Deafult")
{
    ErrorMsg = ErrorMsg + "Please Insert time.<br>";
}
$.ajax({
    url: "/CreateContract/CheckBuyerPublicKeyLegality",
    type: 'POST',
    async: false,
    data : { BuyerPublicKey: buyerPublicKey },
    success: function(data){
        console.log("Buyer balance"+data)
        if (data == -1)
        {
            ErrorMsg = ErrorMsg + "Buyer Public Key is illegal.<br>";//
            console.log("1-->" +ErrorMsg );
        }
    }
});
console.log("2-->" +ErrorMsg );
return ErrorMsg;}