invoking a boolean type JavaScript function

I'm currently working on calling a Page Method using AJAX. Take a look at the code below:

<asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" 
        onclick="btn_upload_Click" OnClientClick="return Validate();" /> 

The Validate method is expected to return true or false. Here's the code for the Validate method:

<script language="javascript">

function Validate()
{   
   var filename = $get('<%= txt_filename.ClientID %>').value;
   PageMethods.IsValidFile(filename,OnSuccess, OnFailure); 
  // IsValidFile is a Page Method of bool return type
}

function OnSuccess(result) 
{
   if ( !result)
   {     
     alert('File '+ $get('<%= txt_filename.ClientID %>').value + ' does not exist');
     return false;
   }
   else
   {      
    return true;
   }
}
function OnFailure(error) 
{   
}
</script>

My issue is that even after displaying the alert 'File somefilename does not exist', the entire page refreshes (a postback occurs).

Answer №1

If you find yourself running an asynchronous operation and still expecting it to block your call and wait for the response, here is a workaround that I have come across in the past: hide your submit button and create another button that triggers your ajax request. In the success of this request, you can then click your hidden button using something like the following code:

<asp:Button ID="btn_upload_dummy" runat="server" CssClass="btnEffects" Text="Upload" OnClientClick="Validate();" />

<asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" style='display:none;' Text="Upload" onclick="btn_upload_Click" />

<script language="javascript">
function Validate() {
var filename = $get('<%=txt_filename.ClientID %>').value;
PageMethods.IsValidFile(filename, OnSuccess, OnFailure);
// IsValidFile is a Page Method returning a boolean value
}

function OnSuccess(result) {
if (!result) {
alert('File ' + $get('<%=txt_filename.ClientID %>').value + ' does not exist');
return false;
} else {
var btn = $get('<%btn_upload.ClientID');
var clicker = btn.click ? btn.click : btn.onclick;
clicker();
}
}


</script>

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

Getting around CloudFlare's 100-second time-out restriction

Seeking a solution to AJAX-enable my reports and circumvent the 100-second time-out constraint enforced by CloudFlare for requests passing through its platform. For more information, visit Is it possible to increase CloudFlare time-out? The implementatio ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

Attempting to delete a request using FormData resulted in a 500 error response

Currently, I am working on deleting an attachment by sending a request with form data containing a URL through an API path along with an ID. deleteAttachment(id, url) { const formData = new FormData(); formData.append('url', url); ...

Utilizing HTML5 data attributes to store intricate JSON objects and manipulate them using JavaScript

Recently, I encountered a unique challenge that I set for myself... I am currently in the process of developing an advanced ajax content loader plugin that comes with an array of options and callbacks. In order to streamline the initialization process and ...

Which is the better option for setting a title: using .prop or .attr?

I came across a comment that mentioned The suggestion was to utilize the .prop() method instead of .attr() when setting the "title" property in jQuery versions 1.6 or newer. Could someone provide an explanation for this recommendation? ...

Insert information into a nested array using Mongoose

I'm encountering an issue with my code, even though I know it may be a duplicate. Here is the snippet causing me trouble: exports.addTechnologyPost = function(req, res){ console.log(req.params.name); var query = { name: 'test ...

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Ways to handle Sessions in Node.js

I'm attempting to utilize a website within node.js. However, the site is prompting me to enable the storage of session cookies. I attempted to set up a cookie-jar, but I couldn't get it to work. Here is a simplified version of the code that is c ...

Exploring AngularJS's capabilities with asynchronous tasks

I am in the process of developing a simple app using AngularJS. One of the key functionalities I am working on is removing items from a list. To achieve this, I have created the following code snippet: $scope.removeItem = function(item) { var toRemove = ...

Creating a Cordova application from the ground up, evaluating the options of using ngCordova, Ionic framework, and

With the goal of creating a multiplatform Cordova app for Android, iOS, and Windows, I have been exploring different approaches. My plan is to build an application with 4 or 5 features focused on service consumption (listing, adding, and editing items) wh ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

What is the best way to incorporate sound into an asp.net web page?

I am trying to add sound effects to my webpage when a button is clicked. However, I keep encountering an error with the following code: SoundPlayer audio = new SoundPlayer(); audio.SoundLocation = "WindowsBalloon.wav"; //audio.Play(); audio.PlaySync(); T ...

Utilizing a dynamically created table to calculate the number of neighbors

I have a challenge where I want to create a minesweeper game with numbers indicating how many bombs are nearby. For example, if there are two bombs next to each other and I click on a cell adjacent to them, it should display the number 2. Likewise, if ther ...

Can someone please provide me with the correct syntax for a jQuery AJAX PUT request that is JSON encoded?

Here is the ajax PUT request that I have written: jQuery.ajax({ url: url_lab_data+"backend/read/{\"f_anid\":"+anid+"}", type: "PUT", data: JSON.stringify({"read": 1}), ...

Refresh the dataTable once all external data has been successfully fetched

I am struggling to find the correct method for reloading a datatable. Here is my current process: Retrieve data through ajax for specific columns Generate a table with the fetched data Initialize the datatable for the table Make a new ajax request using ...

Gathering Servlet details from non-form elements

I am currently in the process of developing an application that is capable of parsing JSON strings. At this stage, I am able to input a JSON string using Java, write it to an HTML document, and then have a JavaScript program read and parse it before ultima ...

Modify the URL query to read as "favicon.ico"

Whenever I make a GET request to my node.js/express web server with a URL following the route, instead of storing that URL, the server ends up saving favicon.ico: var express = require("express"); var app = express(); app.get("/:query", function (req, re ...

Executing a JQuery click event without triggering a page refresh

I'm dealing with a basic form on a webpage <div class="data-form"> <p>Are you hungry?</p> <form> <label class="radio-inline"><input type="radio" name="optradio" value="yes">Yes</label> ...

Why does starting up the Firebase emulators trigger the execution of one of my functions as well?

Upon running firebase emulators:start --only functions,firestore, the output I receive is as follows: $ firebase emulators:start --only functions,firestore i emulators: Starting emulators: functions, firestore ⚠ functions: The following emulators are ...