Using AJAX to refresh a div upon submitting a form, instead of reloading the entire page

My SQL database generates a table that remains hidden until the search button is clicked to display the results.

I want to use ajax to update the table without refreshing the entire page. Currently, when the page refreshes, the table reverts back to being hidden, only briefly showing the content.

$(function () {
    $('#searchForm').on('submit', function () {
        $.ajax({
            type: 'GET',
            url: 'Index',
            data: $('#searchForm').serialize(),
            success: function () {
                $("#resultsTable").removeClass("d-none");
            }
        });
    });
});

Form:

<form asp-page="./Index" id="searchForm" method="get">
    <div class="form-actions no-color">
        <p>
            Find by name:
            <input type="text" name="SearchString" value="@Model.CurrentFilter" />
            <input type="submit" value="Search" class="btn btn-default" id="searchName" />

            @*<a asp-page="./Index">Back to full List</a>*@
        </p>
    </div>
</form>

Although the code above is functional, the page still refreshes. I believe I may have overlooked something.

Answer №1

try using e.preventDefault() to prevent the default form submission behavior.

 $(function () {
        $('#searchForm').on('submit', function (e) {
    e.preventDefault()
            $.ajax({
                type: 'GET',
                url: 'Index',
                data: $('#searchForm').serialize(),
                success: function () {
                    $("#resultsTable").removeClass("d-none");
                }
            });
        });
    });

Answer №2

Make sure to utilize the event.preventDefault() method.

By using the preventDefault() method from the Event interface, you are informing the user agent that the default action of the event should not be taken if it is not explicitly handled. The event will still propagate as usual unless stopPropagation() or stopImmediatePropagation() is called by one of its event listeners.

<input id="search" type="text" name="SearchString" value="@Model.CurrentFilter" />

$(function () {
$('#searchForm').on('submit', function (e) {
    e.preventDefault();
    const search = $('#search').val();
    $.ajax({
        type: 'GET',
        url: 'Index',
        data: { search },
        success: function () {
            $("#resultsTable").removeClass("d-none");
        }
    });
  });
});

Next, in your PHP script:

<?php searchValue = $_GET['search']; ?>

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

Guide to showcasing Laravel Eloquent information using jQuery "Ajax" tooltips?

I am new to Laravel and currently working with an index.blade.php file that contains data in table form: <table class="table table-striped"> <thead> <tr> <td>ID</td> < ...

Invoke a function from a different source in JavaScript

Below is the JS function implemented: function addMemberToLessonDirect(id) { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Automatically fill in an input field with jQuery by using the value from another input field

I am currently working on a loan calculator and am trying to find a way to automatically populate an interest rate field based on the loan amount entered. Here is an example scenario: For amounts ranging from 0 to 100,000, the interest rate is 4.50 For ...

Executing raml2html within an ANT automation script

I have a collection of RAML files stored in a specific folder, and I'm in the process of configuring an ANT script to "generate" them into HTML documentation utilizing the raml2html package which is highlighted on the raml.org website. While my expe ...

My node.js code is not producing the expected result. Can anyone point out where I may be going wrong?

I've been working on a BMI calculator where I input two numbers, they get calculated on my server, and then the answer is displayed. However, I'm having trouble receiving the output. When I click submit, instead of getting the answer, I see a lis ...

How can you pause a YouTube video using jQuery?

My custom jQuery slider consists of three panels that slide smoothly by adjusting their left CSS values. Everything works perfectly, except for one issue - I have a YouTube video embedded in one of the slides, and it continues playing even when the slide i ...

Display MySQL data in a Jade/Pug view by separating it into different sections

Here is the code that generates a list of addresses from the database in the format "123 Hollywood Ave., Los Angeles, California". However, I only want to display 123 Hollywood Ave. I attempted splitting up the address using the split(',') method ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Using a Default Value in a Destructured Function Parameter Results in a ReferenceError

When working on setting a default value for the db in my CRUD functions for testing purposes, I encountered a peculiar issue that has left me puzzled. Here's the snippet of code that caused the trouble: import { db } from './firebase' func ...

Having trouble removing the npm package spotifydl from my system

After running the command npm install -g spotifydl, I discovered that the package was obsolete and no longer functioning properly. Subsequently, I attempted to remove it using npm uninstall -g spotifydl, but instead of completely uninstalling, it kept re ...

Retrieving the selected value from a dropdown using jQuery's `$('#id').val()` may not always provide the desired result

I am having trouble retrieving the selected value from a dropdown menu as it keeps returning either an empty string or undefined results. My HTML code is structured like this: <div class="input-group" style="padding-bottom: 10px;"> <span id= ...

Making an AJAX request using jQuery to retrieve data from an API with dynamic pagination

When making a GET call using Ajax, everything seems to work smoothly and the expected result is obtained. However, there is a limitation of 50 objects in the API being used, along with pagination. My goal is to retrieve all data before calling myFunction(d ...

Adjust the vertical scaling of a container in CSS Grid to maintain aspect ratio similar to an <img>

I am attempting to recreate a demonstration where the house image scales as the viewport height decreases. However, instead of using an <img>, I would like to use a container that also includes absolutely positioned content (unable to provide all the ...

Is there a way to display a message in a div container instead of using the alert box when there is a successful ajax response?

Hey there, I'm currently working on implementing error validation handling for a custom form that I've created. I'm looking to display the error messages in a designated div rather than using the standard browser alert box. Since I'm fa ...

The problem of double encoding in jQuery Ajax issues

Currently, I am attempting to make an ajax call to the server in order to read user input text (which is in Hebrew and utf-8 charset). This is how I have been trying to achieve it: my_url = some_url + textinput my_url = encodeURI(my_url) The issue I am e ...

Social media comments widget

Currently, I am incorporating the Facebook XML to implement a Facebook comments plugin within my MVC 3 application in the following manner: <fb:comments href="@Request.Url.AbsoluteUri" num_posts="15" width="900"></fb:comments> The issue lies ...

Transferring Information from Vue to PHP: What You Need to Know

I need assistance with passing data from Vue to PHP. Currently, I receive a JSON object through a PHP query that looks like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded, ...

How to automatically close the menu on a Wordpress theme after clicking a link

I am currently using a Wordpress theme named ichiban, which can be viewed by following this link. Within this theme, I have created custom menu items that are designed to link directly to different sections on the same page. However, I am encountering an i ...

Ways to eliminate unnecessary re-rendering of components that remain unchanged?

I am struggling with a component that contains various other components, such as text fields. Whenever an input is made in the text field, all the components are re-rendered. My goal is to prevent this re-rendering and only update the component that has a ...