Dealing with numerous Ajax loading issues in ASP.NET MVC

One issue I'm facing involves a dropdown list and a textbox. After selecting a value from the dropdown and entering text into the textbox, clicking the submit button triggers an ajax function that fetches relevant data. The problem arises when clicking the submit button again - the new value loads in the same table without clearing the previously displayed value. How can I ensure that each submission clears the old data before loading the new one?

Jquery:

$(document).ready(function() {
  $("#btnSubmit").click(function(e) {
    e.preventDefault();
    var search = jQuery('[id$=txtsearchType]').val();
    var tittle = jQuery('[id$=txtName]').val();

    if (search != ' ' && tittle != '') {

      if (search == "getgeneric" || search == "getbrand") {
        // AJAX request and response handling for getgeneric or getbrand
      } else if (search == "getcompany") {
        // AJAX request and response handling for getcompany
      } else if (search == "getsubstitue") {
        // AJAX request and response handling for getsubstitue
      } else if (search == "gettherapeutic") {
        // AJAX request and response handling for gettherapeutic
      }

    } else {
      alert('Cannot be blank, must be filled out')
    }
  });

});

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="card">
  <div class="card-block">
    <div class="row">
      <div class="col-lg-4">
        <fieldset class="form-group">
          @Html.LabelFor(model => Model.SearchType, new { @class = "form-label semibold control-label" })
          <select class="select2-arrow" id="txtsearchType" name="searchType">
            <option>-- Select Search Type --</option>
            <option value="getgeneric">Generic Search</option>
            <option value="getbrand">Brand Search</option>
            <option value="getcompany">Company Search</option>
            <option value="getsubstitue">Substitute Search</option>
            <option value="gettherapeutic">Therapeutic wise Search</option>
          </select>
          @Html.ValidationMessageFor(model => model.SearchType, "", new { @style = "color:red" })
        </fieldset>
      </div>
      <div class="col-lg-4">
        <fieldset class="form-group">
          <label class="form-label semibold control-label">Title</label> @Html.TextBoxFor(model => model.ProductName, new { @class = "form-control", @id = "txtName", placeholder = "Search Name" }) @Html.ValidationMessageFor(model => model.ProductName,
          "", new { @style = "color:red" })
        </fieldset>
      </div>
    </div>
    <input type="submit" name="Submit" value="Search" id="btnSubmit" class="btn btn-rounded btn-inline btn-success" />
    <span style="color:green">@ViewBag.Message</span>

    <br />
    <br /> 
    <!-- Tables to display results based on different search types -->
      
  </div>
</section>

Answer №1

if you encounter a syntax error, please feel free to share it with me

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="card">
    <div class="card-block">
        <div class="row">
            <div class="col-lg-4">
                <fieldset class="form-group">
                    @Html.LabelFor(model => Model.SearchType, new { @class = "form-label semibold control-label" })
                    <select class="select2-arrow" id="txtsearchType" name="searchType">
                        <option>-- Select Search Type --</option>
                        <option value="getgeneric">Generic Search</option>
                        <option value="getbrand">Brand Search</option>
                        <option value="getcompany">Company Search</option>
                        <option value="getsubstitue">Substitute Search</option>
                        <option value="gettherapeutic">Therapeutic wise Search</option>
                    </select>
                    @Html.ValidationMessageFor(model => model.SearchType, "", new { @style = "color:red" })
                </fieldset>
            </div>
            <div class="col-lg-4">
                <fieldset class="form-group">
                    <label class="form-label semibold control-label">Tittle</label> @Html.TextBoxFor(model => model.ProductName, new { @class = "form-control", @id = "txtName", placeholder = "Search Name" }) @Html.ValidationMessageFor(model => model.ProductName, "", new { @style = "color:red" })
                </fieldset>
            </div>
...
...
function GetData(search, tittle, successEvent) {
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: 'http://204.93.193.244:8080/apiems/' + search + '/' + tittle,
        //data: "{ } ",
        dataType: "json",
        success: function (data) {
            successEvent(data);
        },
        error: function (result) {
            alert("Error" + result);
        }
    });
};

Answer №2

If your button type is currently set to "submit", consider changing it to "button". Here's an example of how you can modify the code:

<input type="submit" name="Submit" value="Search" id="btnSubmit" class="btn btn-rounded btn-inline btn-success" />
    <span style="color:green">@ViewBag.Message</span>

<input type="button" name="Submit" value="Search" id="btnSubmit" class="btn btn-rounded btn-inline btn-success" />
    <span style="color:green">@ViewBag.Message</span>

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

What is the best method for sending an angularjs $http POST request when a user refreshes a page?

controller: app.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function ($scope, $http) { $templateCache.removeAll(); alert("refreshing....."); $http({ url: '/an ...

Extracting data from nested objects array in React: A step-by-step guide

I am facing an interesting challenge. Currently, I am immersing myself in learning react and have managed to retrieve data from a demo API that I created using Java Spring. Although I am successfully receiving the data in React, my struggle lies in creati ...

Issues arise with the blinking of my table rows

I'm working on a page with a table where certain rows need to blink under specific conditions. This page is a partial view that I load using the setInterval function. However, I've encountered an issue where the blinking functionality goes hayw ...

The autocomplete attribute is not compatible with GroceryCrud functionality

I attempted to implement the autocomplete feature using an example from w3schools. https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_form_autocomplete Although I used jQuery to modify the form and add autocomplete="on" to both the form and input ...

What is the best way to rearrange a sidebar column to be positioned between central content columns on a mobile

I am looking to design a layout with the following components: Left Sidebar Main Content Right Sidebar Extra Content My goal is to achieve the following: On larger screens: Ensure that the "Extra Content" aligns directly below the main content with the ...

Using Node.js to instantly redirect users to a new page while also sending them important

I am currently working on building a basic server for HTML pages using Node.js. The issue I am facing is that when I go to (for instance) http://localhost:8080/someDirectory, the browser mistakenly treats someDirectory as a file (when in reality, it is int ...

Quickest method for duplicating an array in Javascript

I've been exploring efficient methods for creating an array by repeating an element a specified number of times. In my case, the repeated element is usually another array, resulting in a long 2-dimensional array. Speed is crucial for my task, and I&ap ...

Visual Delights on the Menu

I am having trouble adding a "Home" picture to my menu. It keeps showing up as a blank square, even though I have tried using both .png and .jpg formats. Here is the code that I am currently using: <div id='cssmenu'> <link rel= ...

Align the list at the center within a div container

Struggling to align my image gallery within a designated div. Currently facing an issue where the icons appear too small and not perfectly centered. This is the CSS and HTML I currently have: <div id="social"> <ul> ...

Any ideas on how to align the links in the navbar at the center of the image instead of having them at the top?

<!DOCTYPE html> <html> <head> <title>Funky Munky Arcade</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha ...

Is there a way to clear the email form after submitting it, allowing for another email to be sent seamlessly without the need to refresh the

I have been experimenting with a contact form on my Wordpress website. It's functional, but here's the issue... Upon page load, the contact form is empty (obviously). If the text fields are left blank, the form will not send (also obvious). W ...

Which is better: jQuery Mobile templates or PHP templates?

I have a simple web app in the works, consisting of 3-5 pages that are mostly list-based with some single "object" data pages. I plan to use basic templates for these pages and populate them with data from my database using jQuery Mobile. My main question ...

Adjust the width of the scrollbar for the <aside> section

<aside class="sidenav navbar navbar-vertical navbar-expand-xs border-0 border-radius-xl my-3 fixed-left ms-3" id="sidenav-main"></aside> Within this aside element, I have implemented a scrollbar. However, I am seeking to adjust ...

viewing the Jenkins HTML report

I am currently working on a Jenkins job that utilizes the HTML publisher plugin to run selenium automation tests and produces a link to a HTML test result report on the Jenkins job details page. I am seeking a way to share this HTML report link with stak ...

Is there a way to incorporate icons into the rows of a react ag-grid?

I'm currently using the react ag-grid library and I've attempted to use the cellRenderer function, but unfortunately, it's not working as expected. columnDefinationWaterUsage: [ { headerName: "", cellRenderer: count ...

Trouble accessing Facebook Messenger through the integrated browser on Facebook network

My goal is to promote a webpage by sharing it on Facebook Messenger. While everything works smoothly on desktop and mobile browsers, the issue arises when using Facebook's built-in browser - the Facebook Messenger app fails to open and the page just r ...

The function replaceState() is unable to create a history state with a URL in a document that has a different origin

In my main.js file located in required/javascripts on my server, I have the code window.history.replaceState(null, null, 'about');. On the about page (located at the root of my server), there is a link that uses window.history.replaceState(null, ...

Leveraging jQuery to extract numerous concealed data from a webpage based on their names

Here is the scenario: <input type="hidden" name="uID" id="uID" value="251|0"> <input type="hidden" name="uID" id="uID" value="252|0"> <input type="hidden" name="uID" id="uID" value="253|0"> <input type="hidden" name="uID" id="uID" val ...

What is causing the extended duration of Application_ResolveRequestCache?

In my ASP.NET application, I have implemented a trace tool that logs events. The application uses AJAX to retrieve data from controls. Two trace entries are as follows: protected void Application_ResolveRequestCache(Object sender, EventArgs e) { ...

When the ngFor data reaches a count of four, it will be shown in a separate container div

I am struggling to find a way to display my ngFor data in a new container div once the length reaches four. It's easier to hard code the data into separate divs, but using ngFor results in the data being displayed in a single container div. In the co ...