Utilizing ASP.NET AJAX: Enhancing User Experience with ScriptManagerProxy for HTML Button Click Events

I am currently working on a solution for the following issue:

  • Managing the client-side click event of a button - preventing postback if the JavaScript call returns false (e.g.
    onclick="js:return IsThisAllowed()"
    )
  • The JavaScript method will either return true or false based on the result of a call to a generated web service method using ScriptManagerProxy

The code snippet below has been simplified to focus on the key components related to my question. I am able to use alert() to display the return value, but I am struggling with how to pass the response from the web service method call back to the button's onclick handler. Since the function Finish() is executed in a separate thread upon successful completion of what seems to be the XmlHttp.send() call, how can I set the response value as the return value of the JavaScript method? Am I approaching this problem incorrectly?

I have previously used similar code to update the DOM with return values, like within a <div>, however, I have never had to capture the return value and incorporate it into my script.

What I have tried so far:

.NET web service method (VB.NET):

<WebMethod()>
<ScriptMethod()>
Public Function IsAllowed() As Boolean
    Return True
End Function

.NET code for the page to create AJAX web service methods, along with an HTML button

<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
    <Services>
        <asp:ServiceReference Path="~/WebServices/MyWebService.asmx" />
    </Services>
</asp:ScriptManagerProxy>
<asp:Button ID="_btn" runat="server" OnClientClick="js:return IsAllowed();" />

Javascript

<script type="text/javascript">
    function IsAllowed(orderid) {
        if (!processing) {
            processing = true;

            var ws = new MyWebService();
            ws.IsAllowed(Finish, Error)

            // return TRUE if call to IsAllowed returns true!!!

            return false;
        }
    }

    function Finish(result) {
        alert(result)
    }

    function Error() {
    }

</script>

Answer №1

Performing this action can be tricky: when you make a call to the web service, it operates asynchronously and hands control back to the client immediately - which means your JavaScript will likely finish executing before the request is even complete.

Since the timing of receiving a response from ws.IsAllowed is uncertain, you should manage it in your callbacks (Finish and Error).

This applies to any AJAX method you use.

While I'm unsure about the specifics of ScriptManager-based AJAX, one approach could involve reversing the process: instead of halting an ASP.NET button's click event, only proceed with the ASP.NET button if the AJAX call confirms permission.

If using jQuery, consider initiating the AJAX call from a basic HTML button (not an ASP.NET web control). Upon successful completion (similar to Finish), activate the hidden ASP.NET button when the result is favorable.

Answer №2

Have you thought about incorporating jQuery into your project?

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "~/WebServices/IsAllowed.asmx/{Method Name}",
    data: ('{ json serialized data required for decision making }'),
    success: function (msg) {
        alert(msg);
    },
    error: function (request, status, error) {
        alert(err.Message);
        alert(err.StackTrace);
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to handle users with disabled Javascript? Considering redirection to alternate sites for users with script disabled?

I've dedicated today to strategizing the best approach for revamping our company's website, taking into consideration that less than 1% of web users have JavaScript disabled. Our management team strongly believes in ensuring that our website rem ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

Issues with data retrieval from PHP file in AJAX submission

During my attempts to utilize AJAX for submitting data to a PHP file, I encountered an issue where the submission was successful and I could receive a message echoed back from the PHP file. However, when trying to echo back the submitted data or confirm if ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...

I seem to be having issues with the downloaded files for Bootstrap 4. Is there something I am

After creating a site with Bootstrap 4 and downloading all the necessary files, I encountered an issue where Bootstrap was not functioning properly. Strangely, when using the CDN version of Bootstrap, everything worked perfectly. Could I be overlooking som ...

Creating a loading screen in Angular 4: Insert an item into the HTML and then set it to disappear automatically after

I'm dealing with a loading screen that typically takes between 15-30 seconds to load about 50 items onto the page. The loading process displays each item on the page using the message: Loading item x For each data call made to the database, an obser ...

Determine the presence of a value within an array in mongodb

How can I determine if the current Meteor.user()._id exists in the "favoritedBy" array? If true, display "Your favorite", if false, display "Not your favorite". Here is an example document in MongoDB: { "_id" : "W5WwAZatorDEb6DNP", "createdBy" : "aT ...

JavaScript can be utilized to generate an array containing duplicated phrases from a given text

Here's a simple concept: you enter text in a textarea, click "send," and receive a list of recurring phrases. When I say phrases, I mean sequences of two or more words that repeat. While I can identify single words, detecting these phrases is where I& ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

The information was not displayed in the message exchange

I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code: Here's ...

Obtain the response header variable within a Shiny application

In Apache, the LDAP login is passed to a variable called X-Remote-User in the header: https://i.sstatic.net/7jyxO.jpg I am unsure how to retrieve this information in my Shiny app. Does anyone have any ideas? Maybe using JavaScript could be a solution? ...

"Enhance the visual appeal of your Vue.js application by incorporating a stylish background image

Currently, I am utilizing Vue.js in a component where I need to set a background-image and wrap all content within it. My progress so far is outlined below: <script> export default { name: "AppHero", data(){ return{ image: { bac ...

Sending parameters from one Node.js function to another in separate JavaScript files

I am currently working on passing function responses between two Node.js scripts. Here is my approach. Index.js var express = require('express'); require('./meter'); var app = express(); app.get('/',function(req,res){ ...

Empty Data Returned After Sending AJAX Request

Currently, I am delving into the world of ajax in order to simplify my life going forward. I successfully managed to implement an example where a constant array was posted to my controller without any issues. However, when attempting to fetch data from an ...

The asynchronous ajax request is leading to a browser freeze

In the HTML page, I have two sets of a and p elements that are initially set to display:none. At the bottom of the page, there is a function being called with their respective ID's and values, which will enable one of them based on certain conditions ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Enhance your Django website with advanced autocomplete functionality using the powerful django-ajax-selects

I require assistance in integrating auto-complete fields into my Django Project. My goal is to retrieve a list of relevant items from the database as the user inputs their query. For this task, I am utilizing the django-ajax-selects package. The project ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...