www.webdeveloper.com
Results 1 to 3 of 3

Thread: JavaScript - Wait for asynchronous function return value

  1. #1
    Join Date
    Jul 2013
    Posts
    3

    JavaScript - Wait for asynchronous function return value

    Hi there, I am a complete newbie with web development and Javascript, so any help on my code problem will be greatfully received.

    The basic problem is as follows:
    function A {
    status = "is TRUE or FALSE after test 1"
    status = "is TRUE or FALSE after test 2 ... this takes a little bit of time"
    status = "is TRUE or FALSE after test 3"
    }

    JavaScript code flow will wizz down to the last status check while the 2nd one is still processing. It does not wait for each step to complete. Therfore "test 2" does not influence the returned "status" value. I believe this is due to the asynchronous nature of "test 2"? After researching the problem area for many days in Google Land, I think I'm fairly close to a solution. The code fails at the point where function CheckServerSide attempts to return its value to myVar, and hence to the web page call: ClientValidationFunction="MyValidator". Any suggestions on how to do this? Thanks in advance, Pete.

    Consider the following code that follows the process above.
    HTML Code:
     <script type="text/javascript" language="javascript">
    
            function MyValidator(sender, args) {
    
                /* This function checks TextBox input value, and calls a code behind function */
                /* that checks for duplicate records in a database table. The CustomValidator error message  */
                /* is also set conditionally */
    
                var myVar = args.IsValid;
                args.IsValid = true;   /* Set MyValidator return status  */
                var str = args.Value;  /* TextBox input value */
                var myregExp = /^SDLC\d{1,}$/;  /* Input value must start with SDLC and have following digits */
                if (!myregExp.test(str)) {      /* Test input value against rule */
                    sender.errormessage = "Enter valid SDLC";  /* Change Client-Side CustomValidator error message */
                    sender.innerText = "*Enter valid SDLC";    /* Change contents of an HTML error message */
                    args.IsValid = false;   /* Set MyValidator return status  */
                }
                /* Call Server-Side code behind for Duplicates in database table */
                /* setTimeout function waits for 1sec to obtain last validity check */
                myVar = setTimeout(function () { CheckServerSide(args, sender); }, 1000);
            }
    
       </script>
    
        <script type="text/javascript" language="javascript">
    
                function CheckServerSide(args, sender) {
                    var str = args.Value;  /* TextBox input value */
                    PageMethods.Duplicates(str, function (response) {   /* Call onSuccess method "response" */
                        if (response == "Yes") {   /* Returned status from code behind function */
                            sender.errormessage = "Duplicate SDLC found";   /* Change Client-Side CustomValidator error message */
                            sender.innerText = "*Duplicate SDLC found";     /* Change contents of an HTML error message */
                            CheckServerSide = false; /* return function result */
                            alert(CheckServerSide);
                        }
                        else {
                            CheckServerSide = true; /* Validation ok, no duplicates found */
                            alert(CheckServerSide);
                        }
                    });
                }
    
       </script>
    The Web Page code contains a Listview control that makes a call to the JavaScript shown above. This code snippet is shown below:

    Code:
                    <%-- EDIT - SDLC field Validation --%>
                    <td align="center">
                        <asp:TextBox  ID="SDLCTextBox2" style="text-align:center" runat="server" Text='<%# Bind("SDLC") %>' />
                        <asp:CustomValidator ID="CustomValidator2" 
                        ClientValidationFunction="MyValidator"
                        ControlToValidate="SDLCTextBox2" runat="server"
                        ValidateEmptyText="true"
                        CausesValidation="true" 
                        ValidationGroup="EditFields"
                        ForeColor="White" BackColor="Red"
                        Text=""
                        Display="Dynamic"></asp:CustomValidator>
                      </td>

  2. #2
    Join Date
    Jul 2013
    Posts
    3
    Hi, on reading through my original question, the setTimeout part does not make sense. It's the result of many modifications on trying to resolve the problem. Sorry for that! So basically what I'm trying to ask is "how can I get "status" returned that is based on all 3 tests as shown in the following model?

    function A {
    status = "is TRUE or FALSE after test 1"
    status = "is TRUE or FALSE after test 2 ... this takes a little bit of time"
    status = "is TRUE or FALSE after test 3"
    }

    Thanks, Pete.

  3. #3
    Join Date
    Jul 2013
    Posts
    3
    Well judging by there being no response on this one, I realise now that the JavaScript Client-Side approach would be going nowhere. So I've decided to do a workaround for the asynchronous JavaScript problem, and I've posted my own solution to help anyone else who may be having the same problems that I faced.

    This method now works perfectly, after many days of hacking around with the code!

    <script type="text/javascript" language="javascript">

    function MyValidator(sender, args) {
    /* This workaround method overcomes the asynchronous problems
    of JavaScript not waiting on conditional statement outcomes.
    The aim is to push all conditional checks and outcomes to
    Server-side where no asynchronous problems occur. Then return
    a string message back to Client-Side indicating which conditional
    check failed. Appropriate Client-Side error messages can then be
    generated, and returned to the ListView input textbox in my example.

    To call Server-Side code from JavaScript, you can use ASP.NET
    AJAX Extensions. Then use "PageMethods" to call Server-Side
    functions using JavaScript

    Call Server-Side code behind function "DoChecks" */
    var str = args.Value;
    PageMethods.DoChecks(str, function (response) { /* Call onSuccess method "response" */
    if (response == "Start with SDLC") { /* Returned error message */
    sender.errormessage = "Start with SDLC"; /* Set Client-Side CustomValidator error message */
    sender.innerText = "*Start with SDLC"; /* Set contents of HTML error message */
    return args.IsValid = false; /* Set MyValidator return status */
    }
    else if (response == "Digits must follow") {
    sender.errormessage = "Digits must follow";
    sender.innerText = "*Digits must follow";
    return args.IsValid = false;
    }
    else if (response == "Duplicates found") {
    sender.errormessage = "Duplicates found";
    sender.innerText = "*Duplicates found";
    return args.IsValid = false;
    }
    else if (response == "All OK") {
    return args.IsValid = true;
    }
    });
    /* Must have the following alert for some reason, probably
    waiting for Client-Side asynchronous code to catch up!) */
    alert("Error with: " +str);
    }

    </script>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles