Updating textbox values with ajax results in the page refreshing and the newly assigned values being lost

I'm currently working on updating a section of my webpage using AJAX instead of C#, as I don't want the page to refresh. All I need to do is execute a SELECT query to retrieve the current client from the SQL database and populate the corresponding form without refreshing the entire page. I've been able to successfully fetch the client data and update the textbox, but unfortunately, the page still refreshes afterwards and all the textboxes end up empty again!

Below is the code snippet I'm using:

    <asp:Panel ID="pnlClientSummaryDetails" runat="server" Width="360px" Visible="True">
       <asp:TextBox runat="server" ID="txtDateOpened"></asp:TextBox>
       <!--other text boxes -->
    </asp:Panel>

    <asp:Button ID="bnSelectClient" runat="server" CssClass="auto-style7" Text="Select Client" ToolTip="Click the view client button to view selected clients information" Width="282px" OnClientClick="BindClientSummaryForm()" />

    function BindClientSummaryForm() {
            $.ajax({
                type: "POST",
                url: "Clients.aspx/GetClientSummaryData",
                contentType: "application/json;charset=utf-8",
                data: {},
                dataType: "json",
                success: function(data) {
                    document.getElementById('<%= txtDateOpened.ClientID %>').value = data.d.DateFileOpened;
                  // other textboxes will be filled like that.
                },
                error: function (result) {
                    alert("Error occurred while filling ClientSummary part.");
                }
            });
        }

[WebMethod] 
        public static MyClient GetClientSummaryData() //GetData function
        {
            //FillClientSummaryGridView();
            int intClientID = 0; 
            Int32.TryParse(clientID, out intClientID);
            MyClient client = new MyClient();
            string sQuery = "SELECT ClientID,FirstName,DateFileOpened FROM dbo.Client where ClientID = " + intClientID;
            String sConnectionString = ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString;
            SqlConnection con = new SqlConnection(sConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(sQuery, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtGetData = new DataTable();
            da.Fill(dtGetData);

            foreach(DataRow dtRow in dtGetData.Rows)
            {
                client.Firstname = dtRow.ItemArray[1].ToString();
                client.DateFileOpened = dtRow.ItemArray[2].ToString();            
            }
            return client;
        }

I'm seeking advice on how to prevent the page from refreshing and retain the values in the textboxes assigned by the AJAX success function. Any help would be greatly appreciated. Thank you!

Answer №1

Consider implementing return false in your BindClientSummaryForm function after the ajax call. Additionally, adjust how you invoke the function like so: OnClientClick="return BindClientSummaryForm();"

If this adjustment does not yield results, attempt eliminating return false from the function and employ this method instead: OnClientClick="BindClientSummaryForm(); return false;"

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

retrieving the file directory from a folder with the help of ajax

I am having trouble retrieving a list of files from a specific URL that lists files inside a folder: https://i.sstatic.net/VH22b.png In order to obtain this list of files using JavaScript, I have written the following code: $.ajax({ url: &ap ...

Transmit information to the server using AJAX

Can anyone help me with an issue I'm having? The code below isn't working and I can't figure out why. I saw it in a youtube video, but still struggling to get it running. I am using a WAMP Server at 127.0.0.1 and it's strange that the b ...

What's the best way to implement two AJAX field validations to prevent button redirection on a website?

Can anyone provide guidance on how to implement two ajax field validations for a button to prevent clicking if the data already exists or redirecting to the same page? I am seeking assistance with this issue. Below is the ajax code snippet: function vali ...

Is it more effective to utilize Selenium or simulate an XHR request when using Python Scrapy?

I am looking to extract data from a large online marketplace website that utilizes ajax pages. My plan is to deploy this on a Centos VPS so I can regularly gather data and improve my product offerings. While I am inexperienced with Python, Scrapy, and web ...

JSON representation of the directory structure

Is there a way to generate a Json representation of a local directory? When I specify a folder, I would like to view all its subfolders and files in a json tree structure. Important: I am not looking for a simple list of file paths. Thank you! ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

jQuery GET request is not functioning properly in Internet Explorer

Here is the jquery code snippet that I am currently using: function update() { $.get("getlatest.php", { id: $.cookie('last_post_id') }, function (response) { $('#board_posts').prepend(response); $(' ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...

Deciphering the hidden power of anonymous functions within Express.js

Recently, I started learning about express and am grappling with understanding callbacks in RESTful actions. In the following PUT request code snippet, I am puzzled by the specific line that is highlighted below. Why is response.pageInfo.book being assigne ...

What are the steps to implement server side routing using react-router 2 and expressjs?

If you're looking to delve into server side rendering with react-router, the documentation linked here might fall short in providing a comprehensive understanding. In particular, it may not offer enough insights on how to leverage react-router 2 for r ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

Tips for properly aligning an image within an owl carousel

Currently, I am attempting to center a small image within the owl carousel. While I have managed to center it when it's active and in the center, I'm encountering issues when the item no longer carries the "center" class. You can access Owlcarou ...

How to Send and Receive Data in One Request Using Android Studio and Web API

Currently, I am working on an Android App using Android Studio and the backend is being developed using Asp.Net Web API. Web Api Part [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public dynamic GetTest(string name) { List< ...

Tips for passing parameters in the $http GET request to transmit information from a dropdown menu using AngularJS

In the modal window I have for creating a new object, there are three forms: 1) a simple input to create "Name"; 2) A dropdown with "Types"; 3) A dropdown with "Ids". The issue arises when trying to send the data after filling out all the forms. An error o ...

What is the correct way to establish an array variable containing objects?

What is the correct way to declare an object within an array variable? I encountered the following error message: "TypeError: Cannot set property 'name' of undefined" Here is the code snippet in question: let data = [] data[0].name = "john" ...

Tips for including HTML tags within a string using node.js, express, and ejs

Currently, I am utilizing Node.js with Express and EJS for my project. My goal is to pass HTML tags within a string to the browser in the following manner: listRequests.forEach(function(key) { messages.push("You have a message from <b>" + key.us ...

Upgrading the monitoring page by implementing a more efficient alternative to AJAX calls

Issue at Hand I have put together a complex project utilizing PHP and Laravel on the backend. Users on the website can indicate their availability to respond to calls, which are stored in a MySQL database. Currently, this system is running on a shared web ...

Restrict server routing in asp.net to only allow api calls

After successfully setting up an Angular 2 project using ASP.net with WebAPI, I encountered an issue while routing within Angular 2. When trying to access a specific route, such as "localhost:1234/login", the page displayed the following error: HTTP Err ...

Issues with string encoding after using NSUTF8StringEncoding

When attempting to download a JSON string from a server, I noticed that the formatting is not as expected. Apologies for the confusion, I am new to using Stack Overflow. Upon comparing the received string with the var_dump output from PHP, I observed that ...

Utilizing Vue Js and Query to retrieve data from a Jira Rest API endpoint

Trying to utilize the JIRA REST API within a Vue.js application has presented some challenges. After generating the API key, I successfully ran an API request using Postman. Initially, I attempted to use the axios client, but encountered issues with cross ...