After the initial jQuery ajax request, the jQuery formatting adjustments are reverted back to their

It seems like there are others facing similar issues without finding a solution. Here is the situation:

The user clicks a button to reveal a hidden div that contains a textarea for making comments:

//revealing the textarea-containing div
$('#postTypeContainer').css({ 'display': 'block' });

Then, the user inputs a comment, submits it, hides the div, and sends data to the server:

$("#loading").ajaxStart(function () {
        $(this).show(); //displays a spinner
    }).ajaxComplete(function () {
        $(this).hide(); //hides the spinner

        //hiding the previously opened div
        $('#postTypeContainer').fadeOut('fast');
    });

    //sends data
    $.ajax({
        type: "POST",
        url: rootUri + "main.aspx/StartNewThread",
        data: jsonText,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (markUp) {
           //doing stuff
        }
    });

All of this functions correctly.

Next, the user reopens the div by clicking on it, which works as expected

//revealing the textarea-containing div
$('#postTypeContainer').css({ 'display': 'block' });

Then, the user enters some data, such as @abc to tag another user, and using jQuery on 'keyup', the following happens:

//ajax call to find users matching the @abc
$.ajax({
        type: "POST",
        url: rootUri + "main.aspx/GetMatch",
        data: jsonText,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {

            //handling the response data

        }
    });

After this ajax call completes, the previously opened div suddenly closes, almost as if the DOM is reverting back to its initial state before the ajax call. This abrupt closure of the div while trying to interact with the textarea can be frustrating for the user. The only workaround seems to be refreshing the page, but that defeats the purpose of using ajax. Any insights on what might be causing this issue would be greatly appreciated. One unsuccessful attempt I made was checking the div's state within the keyup function responsible for the ajax tagging call and trying to keep it open at the end of the call, but that did not work as intended. Any assistance would be welcomed.

Answer №1

.ajaxComplete() is a global ajax event that triggers every time a jQuery ajax event finishes. Therefore, when the second ajax call is completed, it also hides the postTypeContainer div. To achieve the desired outcome, you should bind this hiding action to the local complete event for the first ajax call.

$("#loading").ajaxStart(function () {
    $(this).show(); //displays a spinner
}).ajaxComplete(function () {
    $(this).hide(); //removes the spinner
});

//send data
$.ajax({
    type: "POST",
    url: rootUri + "main.aspx/StartNewThread",
    data: jsonText,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (markUp) {
       //perform operations here
    },
    complete: function() { // PERFORM ACTION HERE

        //hides the previously opened div
        $('#postTypeContainer').fadeOut('fast');

    }
});

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

When saving, Vue sporadically creates misleading error messages

Recently, I started a new Vue project that wasn't very populated. When I run the command below, everything runs smoothly... npm run serve However, as soon as I make a small change in my project and hit CTRL+S, the Vue instance is rebuilt and strange ...

How to Fix Items Being Pushed Down by 'Particleground' Jquery Plugin Due to Z-Index and Positioning

I'm grappling with understanding z-index and positioning, despite reading various questions and articles on the topic. Currently, I'm attempting to incorporate a Jquery Plugin called 'Particleground': https://github.com/jnicol/particle ...

jQuery.post() function encounters issues with data not being properly posted

I am currently tackling a project that involves sending JSON data to a specific URL. I've been attempting to utilize the jQuery.post() method for this task, but I've run into a couple of roadblocks. The initial issue I'm facing is: jQuery. ...

Adjust the height of each card dynamically based on the tallest card in the row

I am working on a row that looks like this: <div class="row"> <div class="col"> <div class="card"> <div class="card-body"> <h3 class="card-title ...

Mastering JavaScript Testing with Selenium 2

I am currently experimenting with JavaScript in Selenium 2 WebDriver using Visual Studio 2010. Are there any effective methods to call a function that is part of the current JavaScript object on the page? ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...

Issue with SweetAlert2 cancel button being unresponsive while an ajax request is in progress

I have a custom function triggered when a dropdown item is selected, which triggers a sweetalert2 popup. Here's the function: function SwalPopup(ip, method) { var methodmsg = method.charAt(0).toUpperCase() + method.slice(1); swal.fire({ ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

What is the method used by threejs to position a mesh within a scene when no coordinates are provided?

I'm embarking on a personal project using threejs and I'm seeking clarification on how the threejs add method functions when adding to the scene. In a small example, a scene and camera are created with near and far plane units set from 0.1 to 10 ...

Unable to render Javascript model in THREE JS

I am facing an issue with this code below as I can't seem to load the model. loader = new THREE.JSONLoader(true); loader.load("modelo.js" , function ( geometry, materials) { mesh = new THREE.Mesh( geometry, ...

Calculating the total sum of values from keys, post applying the filterBy method

HTML: <div id="app"> <h1>{{title}}</h1> <form id="search"> Filter <input name="query" v-model="filterQuery"> </form> <table> <tr v-for="client in clients | filterBy filterQuery"> <td ...

retrieve trackpoint information using OpenLayers

When displaying a map with a GPX track using OpenLayers 5.3, I noticed that the trackpoints default to a MultiLineString geometry type. The example provided in the GPX-example actually has a larger file size because all of the <trkpt> tags are duplic ...

Issue encountered while attempting to save the date to a json file

While working on my code to directly print the date from index.js into data.json, I encountered an error stating that data is not defined. This is what I have done so far: Ran npm init Installed jsonfile using npm i jsonfile index.js const json ...

Is there an npm module available that can automate a daily task at a specified time in a Node.js environment?

Searching for an NPM Module to integrate into a Node.js application that can send notifications via email and SMS daily at 9am local time. Any suggestions or solutions would be greatly appreciated! ...

Enhancing modal interactions with modal pop-ups

I've been experimenting with different modal effects for a modal popup, following the examples on this site: https://tympanus.net/codrops/2013/06/25/nifty-modal-window-effects/ Here is my code snippet: <div class="md-modal md-effect-1" id="modal- ...

The sorting of elements using the jQuery sort() function encounters issues on webkit browsers

Looking for a solution to sort elements by a number? Consider this part of a function that does just that. The number used for sorting is fetched from a data-ranking attribute of the element: $(".tab_entry").sort(function(a,b){ return parseFloat(a.dat ...

Troubleshooting: Issue with binding nested data property using bracket access in Vue3 v-model

Having an issue in Vue3 where I am unable to bind a nested property to v-model correctly. Check out the source code below: Template: <div id="app"> <span>{{level1.level2.level3}}</span> <br/> <span>{{level1[&ap ...

The button is not being vertically centered when using the boostrap pull-right class

---------------------------------------------------------------- | Title | | Button | --> (using .pull-right) the button is not aligned vertically ------------------------------------------------------------- ...

Choosing a menu option with jQuery

Can someone help me with making a menu option selected in HTML? Here is my code: <ul class="ca-menu"> <li> <a href="#"> <span class="ca-icon"><img src="images/home.png" ...

The function user.user.sendEmailVerification in React Native Firebase for email verification is not supported

I have been working on developing an app with Firebase integration. Below is the code snippet that I am using: const user = await createUserWithEmailAndPassword(auth, email, password) await user.user.sendEmailVerification() While trying to initialize the ...