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

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

Tips on safeguarding your templates while working with SailsJS and AngularJS

I am currently working on a web application using SailsJS and AngularJS. My project requires session management to track user login status. I came across this helpful tutorial and implemented an index.ejs view located in the /view folder. Within the index. ...

Switch up the color of the following-mouse-div in real-time to perfectly complement the color that lies underneath it

I am trying to create a div that changes color based on the complementary color of whatever is underneath the mouse pointer. I want it to follow the mouse and dynamically adjust its color. This functionality is similar to what Gpick does: https://www.you ...

Observing for form input in Nuxt.js

There is a form on my webpage, which includes the following elements: <div v-if="this.userdata.address == ''">Please enter your address</div> Your address <input type="text" v-model="userdata.address" ...

What is the best way to incorporate JQuery into html content retrieved through an ajax request?

In my jsp file, there is a div structured like this : <div id="response" class="response"></div> After triggering an ajax call to a servlet, the content of this div gets updated with the following elements : <div id="response" class="res ...

PHP - Struggling to insert data in the appropriate time format

Currently working on a scheduling program and looking to utilize Ajax for inserting hours into my database. When hardcoding the insertion, everything works perfectly fine. However, when using an array, it seems like json is altering the data - causing the ...

Iterating over an array of lists to tally the elements

I've been struggling to count the number of objects in an array using JavaScript. Below is the array I'm trying to work with: <script> var arr = [ {"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam", ...

Initiating an Ajax POST request when the onblur() event is triggered

Having an issue with Ajax. I'm trying to submit a changed value from an input field on the onblur() event, but there's a flicker that's bothering me. When I enter a new value and click away, the old value briefly flashes back before changi ...

Issue: A React component went into suspension during the rendering process, however, no alternative UI was designated

I'm currently experimenting with the code found at https://github.com/adarshpastakia/ant-extensions/tree/master/modules/searchbar Although I followed the tutorial instructions, I encountered an error. Could it be that the library is malfunctioning? I ...

What is the best method for converting a string picture URL into an image and showcasing it in an image tag?

I have a URL for an image that looks like this: C:\inetpub\MaujApp\OMSAPI\ManualReceivingImages\WhatsApp Image 2021-03-24 at 12.07.41 PM.jpeg My goal is to convert the original image and display it to the user using jQuery. I woul ...

Tips for maintaining a scrollable Material-UI Table with dynamic height?

I'm encountering an issue with the Material-UI Table component in terms of its size and scrollability. Summary: The Material-UI table only becomes scrollable when its parent has a fixed size. If I set the size to 100% to fit the parent, it overflows. ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

Show information from database in a drop-down menu utilizing jQuery

tbl_fruits id | name | 1 | banna | 2 | apple | 3 | orange | 4 | kiwi | Currently, I have an HTML script that includes a form for adding users: <form id="form-add_users" autocomplete="off"> &l ...

Showcase a picture within a row of a table using Ajax in an MVC framework

Getting straight to the point, I have a similar code snippet in my Controller: return base.File(getSomeImageBitmap, "image/jpeg"); This code successfully displays the image in a new window using @Html.ActionLink. However, I want the image to be directly ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Blending Angular5 and AngularJS in Polymer

We are considering launching two new projects - one using Angular 5 and the other utilizing Polymer. The second project is intended to serve as a component library for reuse in not only the Angular 5 project but also in other AngularJS projects. After res ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

Tips for updating the content of a DIV element on a separate page

One question that often arises is how to change the content of a div element on a different page within a website. While it is common to use Ajax to dynamically update div content within the same page by fetching data from an external .html file, the proce ...

I can't seem to establish a connection with my MongoDB Atlas cluster. I encountered the MongooseError, which is as follows:

Error [MongooseError]: The uri parameter for the openUri() method needs to be a string but is currently set as "undefined". Please ensure that the first parameter for mongoose.connect() or mongoose.createConnection() is a valid string. const express = r ...

The specified property 'slug' is not found within the designated type 'ParsedUrlQuery | undefined'

I am faced with an issue in my code where I am attempting to retrieve the path of my page within the getServerSideProps function. However, I have encountered a problem as the type of params is currently an object. How can I convert this object into a stri ...