Tips for Running a Function Once an Ajax Request is Finished

I have a requirement where I need to execute the second function after the completion of an AJAX call in the first function (which involves reloading the page). Can you assist me with this? Here is the code snippet:

<div id="exapnd_or_collapse_div" class="exapnd_or_collapse_div" onclick="changeLayout();">
<script>
function changeLayout () {
    alert('change layout');

    try {
        jQuery.ajax({
            url:'<%=resourceURL.toString()%>',
            dataType: "text",
            data:{
                <portlet:namespace  />cmd:'changeLayout'
            },
            error: function(){
             alert("AJAXError");
            },
            type: "post",

            success: function(data) {

                if("success" == data) {

                    location.reload();
                }
            }
        }).done(function(){
            exapndCollapse(); 
          });


    } catch(e) {
        alert('waiting: ' + e);
    }
};

function expandCollapse() {


            jQuery("div.Search_Styled-dropDown").css("display", "none");
            jQuery("span.menu-text").css("display", "none");

            jQuery("ul.Common_ul").css("display", "none");
            jQuery("img.module_images").css("width", "25px");
            jQuery("img.module_images").css("margin-top", "20px");
        jQuery("img.module_images").css("height", "21px");
            jQuery("#search_box").css("display", "none");   
        jQuery("#Escaped_toggle").css("margin-right", "94%");   
        }
</script>

Answer №1

As you may be aware, Ajax is used to make asynchronous requests, allowing the client to continue without waiting for a response from the server. During this process, the Ajax object goes through various states (ranging from 0 to 4). These states are defined as follows:

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request finished and response is ready

To address your specific requirements, there are two potential solutions:

  • You could opt for synchronous requests (although not recommended)
  • You should call your second function when the readystate value reaches 4

Below is a code snippet that could guide you:

function changeLayout() {
    try{
        jQuery.ajax({
            url:'<%=resourceURL.toString()%>',
            dataType: "text",
            data:{
                <portlet:namespace  />cmd:'changeLayout'
            },
            type: "post",

            beforeSend: function(){
                // This method will be executed before sending the request
            },
            success: function(data) {
                // This method will be executed upon receiving a successful response.
            }
            complete: function(){
                // This method will be executed after completing the request.
            },
            error: function(){
                // This method will be executed if an error occurs.
            }
        });
    }catch (e) {
        alert(e);
    }
}

We hope this information proves useful to you :)

Answer №2

Give this a try, I have provided an example but make sure to customize the code based on your needs

function toggleView(){

    //add your script here
    //if you need to reload the page, add it in this section

}

function adjustDesign () {
var variable = 'example';
    $.ajax({
          url:'script.php',
          type: "POST",
          data: {"variable":variable},
          success: function(data){
              //execute actions after successful ajax call 
              toggleView(); //make sure to adjust the function call accordingly
          },error: function() { 
              console.log("error");
          } // This will be triggered every time there's an error
   });   
};    

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

Tips for setting up my ajax/views method to output a dictionary

Here's the HTML snippet I have along with an AJAX request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"end ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

Having trouble running react-native on iOS?

I am currently following the lesson on this website Versions used: npm 5.4.2 homebrew 1.3.3 react-native-cli: 2.0.1 react-native: 0.48.4 watchman 4.9.0 node v6.6.0 The commands I have executed are: admin@admin  ~/Documents/ReactNativeLear ...

All elements of the Jquery Accordian are receiving identical data appends

This is a program showcasing an accordion feature. The accordion is being created with sample data. When the accordion element is clicked, the click event is captured, then an XML file is loaded and the data is appended to the div. However, the issue ari ...

Having trouble updating the text in a div tag located above a specific button?

Hey there! I am using a RoundedButton component with a div tag for setting dynamic text, followed by a button. In my App.js, I have utilized this component thrice. However, when a user clicks on any button, the "User selected" text should display above th ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

Tips for displaying an alert in the upcoming event loop

I recently started learning VueJS and decided to create a practice game to strengthen my understanding of the framework. http://jsfiddle.net/mzref4o0/1/ Within this game, the attack method is crucial in determining the winner: attack: function(isSpecial ...

Sending variable data through AJAX: A comprehensive guide

After sending the variable data through ajax to the loading_add.php page, I encountered an error message: Uncaught ReferenceError: profit is not defined. Below is what I have attempted so far: var profit = ( Number($("#pro_price").val() - retail_pri ...

Creating your own unique CSS animation or transition timing function is a great way to add a

When it comes to CSS timing functions, they often appear to exist between two specific points: https://i.stack.imgur.com/qyvON.png Even with the option of using custom bezier curves, the curve created can only transition from one point to another. https ...

How to transfer input value from textbox to a div using Vue.js

I am attempting to trigger a function when a button is clicked. Furthermore, the value from the text box one should be displayed in a div. Sample code: <input v-model="textdata" type="text" class="w-full rounded"> < ...

How can I properly update a TimeStamp column in PostgreSQL using Node JS?

I am trying to update the timestamp column in my PostgreSQL database using the following code: function updateStatusCreated(request, response, next) { const date_generation_file = new Date(); pool.query( `UPDATE data SET report_status = &ap ...

Enzyme 3 accesses the properties of the displayed DOM element

After retrieving the HTML with myDomNode.html(); <div aria-expanded="true"> {{someChildren}} </div> I need to verify that the aria-expanded attribute is set to true in my test. Previously, with enzyme 2.x and react 15.x, this code worked fin ...

Enabling the jQuery auto-complete plugin for automatic submission

I am currently facing two challenges with using JQuery autocomplete in PHP: 1. I want the form to auto-submit when I select an option, instead of requiring multiple enters. 2. Even if there are no new options available, it still shows outdated suggesti ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Using Jquery to target images within the viewport based on their class name

I have a webpage that contains various images. I'm looking to add an animation effect to these images when they come into view as I scroll down the page. Here is my current approach: $.fn.is_on_screen = function(){ var win = $(window); var vi ...

Guide to applying a class to a bar with jQuery

Is there a way to dynamically add a class to the bar element when a user hovers over it? The current code I have deployed is not producing the desired output. In CSS, we can use ".bar:hover:before" to target elements in a similar manner. How can I achieve ...

What causes an image background to take precedence over the background color of Bootstrap buttons?

Why is the CSS overriding the bootstrap button background styling and making it transparent instead of the default color? For example, if I have a button with the following styling in my document that sets the background-image of the entire body to an ima ...

There seems to be an issue with the functionality of flatlist and scrollView

I am new to working with react-native. I have a screen where I am using four flatlists, but the last flatlist at the bottom of the screen is not scrolling. I added a scrollView and it worked fine, but now I am getting this error message: VirtualizedLists ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

Looping through an array of objects in VueJS can become a bit tricky when dealing with objects whose properties are dynamic. How can I efficiently

I am looking to create a matrix display from an array of objects, but the properties of the objects may change over time. Here is an example of the data: [ { location: "Japan", webhookStatus: "Up", authenticationStatus: &q ...