What could be causing my search form to fail to perform the search initially?

Isn't it strange that my search form doesn't work correctly the first time? You have to search again for it to function properly. Is there something wrong with my code?

Fiddle

HTML

<form id='sform' action="/admin/search.php" method="get">
    <input id="search" placeholder="Enter your group name..." type="search" name="s" value="" />
    <p></p>
    <input type="submit" style="display:none;" />
</form>

CSS

/*search bar*/
 #sform {
    display:inline-block;
    position: relative;
}
#search {
    border: 4px solid #999;
    cursor: pointer;
    height: 10px;
    padding: 8px;
    position: relative;
    width: 10px;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
    border-radius: 15px;
    -moz-appearance: none;
    -webkit-appearance: none;
}
#search:hover {
    border-color: #199ed9;
}
#search:focus {
    border-color: #199ed9;
    outline: none;
    width: 180px;
    -moz-transition: all .2s ease-in-out;
    -webkit-transition: all .2s ease-in-out;
}
#search.searching {
    margin-left: 80px;
    width: 10px;
    -moz-transition: all .2s ease-in-out;
    -webkit-transition: all .2s ease-in-out;
}
#search + p {
    background: #999;
    content:'';
    cursor: pointer;
    display: block;
    height: 10px;
    position: absolute;
    right: 10px;
    top: -22px;
    width: 4px;
    -moz-border-radius: 1px;
    -webkit-border-radius: 1px;
    border-radius: 1px;
    -moz-transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
    -moz-transform-origin: center 20px;
    -webkit-transform-origin: center 20px;
}
#search + p:hover, #search:hover + p, #search:focus + p {
    background: #199ed9;
}
#search.searching + p {
    -moz-animation: rotateHandle .6s linear 6;
    -webkit-animation: rotateHandle .6s linear 6;
}
@-webkit-keyframes rotateHandle {
    from {
        -webkit-transform: rotate(135deg);
    }
    to {
        -webkit-transform: rotate(-225deg);
    }
}
@-moz-keyframes rotateHandle {
    from {
        -moz-transform: rotate(135deg);
    }
    to {
        -moz-transform: rotate(-225deg);
    }
}
/*end of search bar*/

JS

$(function (){
//expand search bar
var okToSubmit = false;
$("#sform").submit(function (e) {
    if (!okToSubmit) {
        e.preventDefault();
        $("#search").addClass('searching').val('');
        var url = $(this).attr('action');

        setTimeout(function () {
            $.ajax({
                type: 'POST',
                url: url,
                data: $(this).serialize(),
                timeout: 8000,
                success: function (r) {
                    $("#search").removeClass('searching');
                }
            });
            okToSubmit = true;
        }, 8000);
    }
});
});

Answer №1

The issue stems from the asynchronous nature of ajax. The "A" in Ajax stands for Asynchronous, meaning you cannot predict the order of execution or guarantee that the ajax request will finish within 8 seconds.

It is important to place okToSubmit inside the success handler and modify your code as follows:

function doAjax() {
    $.ajax({
        type: 'POST',
        url: url,
        data: $('#sform').serialize(),
        timeout: 8000,
        success: function (r) {
            $("#search").removeClass('searching');
            okToSubmit = true;
        }
    });
    setInterval(doAjax, 8000);
}

Then invoke the function like this:

$(function () {
    //expand search bar
    var okToSubmit = false;
    $("#sform").submit(function (e) {
        if (!okToSubmit) {
            e.preventDefault();
            $("#search").addClass('searching').val('');
            var url = $(this).attr('action');
            doAjax();
        }
    });
});

This approach ensures that one request completes before initiating the next one.

If you are using a jQuery version older than 1.8, consider adding the async:false attribute to your $.ajax({});

Answer №2

The current solution appears to be functioning correctly now:

    $("#search-form").submit(function (event) {
                    $("#search-bar").addClass('active');
                    var searchUrl = $(this).attr('action');
                    $.ajax({
                            type: 'POST',
                            url: searchUrl,
                            data: $(this).serialize(),
                            timeout: 8000,
                            success: function (response) {
                                    $("#search-bar").removeClass('active');
                            }   
                    }); 
    }); 

Answer №3

The solution is functional within the provided fiddle. It is imperative to exclude the .val('') method, as it clears the value before submission.

    let readyToSubmit = false;
    $("#sform").submit(function (e) {
        e.preventDefault();
        if (!readyToSubmit) {
            $("#search").addClass('searching');
            let url = $(this).attr('action');
            setTimeout(() => {
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: $(this).serialize(),
                    timeout: 8000,
                    success: function (r) {
                        alert('Search result: '+ r);
                        $("#search").removeClass('searching');
                        readyToSubmit = true;
                    }
                });
            }, 8000);
        }
    });

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

Why is my client program not receiving a response from this socket.io server?

Currently, I am in the process of developing a trivia game where two users engage in answering questions with the winner being declared at the end. As part of this project, I have integrated socket.io to facilitate the exchange of answers. However, I have ...

Execute JavaScript function only if it is the final invocation

I'm currently experiencing an issue with a Javascript function that updates a bootstrap spinner. The function works well in general, but the problem arises when I click multiple times. I utilize ajax to update the quantity of selected products in the ...

Filtering a JSON array with the PHP $_POST array

Currently, I am dealing with a json file that holds detailed vehicle information: array_filter, after selecting Ford, the Chevy vehicles are excluded from the results. So if I choose Ford and Red, I will only get one result as expected - a red Mustang. H ...

Utilizing jQuery's multiselect feature in the user registration form of a web2py website

Is there a way to incorporate jquery.multiselect.js into the db.auth_user table or default/user/register page? I have been trying to figure it out, but not sure how to modify the html page or controller to make it work. auth.settings.extra_fields['au ...

Changing the style of a single element in various components in Vue

I need to alter the design of a specific div that is used in different components within my Vue.js application. The #app div should have a padding of 172px only in the Hello.vue component, while it should remain at 0px in all other components. Is there a w ...

Could we incorporate a backwards typewriter animation?

Is there a way to delay this animation for 2 seconds before playing in reverse? I came across this online and made some edits, but I'm still new to this (early stages). Can this be achieved using CSS, HTML, and JavaScript? I plan to use this as an ale ...

Adjust grid column sizes automatically when a smaller number is declared - tailwind

I am working with the tailwind grid system and have specified 6 columns for each row. However, if the number of elements is less than 6, I would like it to resize them to 3. <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 grid-flow-r ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...

Ways to change specific CSS class properties in a unique style

As a Java programmer using primefaces 5.1, I've encountered some challenges with handling CSS classes. One particular issue I'm facing is the need to override certain CSS properties to remove the rounded corners of a DIV element. The rendered cod ...

Hover effects on the navigation bar combined with an image featuring a sub navigation menu

Looking to craft a dynamic navigation bar that switches out subcategory images on hover. (subcategories come pre-loaded with images) ...

Tips for displaying HTML elements beyond the boundaries of an iframe

Similar Inquiry: How can content from an IFRAME overflow onto the parent frame? I am in search of a potential solution for the following issue: There is a specific element with the style "position: absolute" within a page loaded into an iframe. Based ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

The success function in $.ajax not being triggered

In the .js file, there is a function that invokes a webservice method named getStudents: [WebMethod(Description = "white student list")] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public List<Job> getStudents(long classId) ...

Submitting content without needing to refresh the page occurs when clicking on a link rather than a button

I am sending parameters from one page to another so that they can be inserted into a table when a link is clicked. I'm interested in knowing if it's possible to use AJAX to call the insert script when text is clicked. I know this can be done with ...

CSS hover effects are malfunctioning

Having an issue with hover in CSS. Attempting to create a menu bar using saved PNG files, each file within its own div. When applying a class name and hover modifier, it only works on the first element. As the pointer moves to subsequent elements, they are ...

Creating a bare JSON request in Express 4.13 using the body-parser middleware

My Express server is set up with the following parameters and routes: var express = require('express'); var bodyParser = require('body-parser'); var router = express.Router(); var app = express(); app.use(router); app.use(bodyParser.ur ...