When trying to revert back to the original content after using AJAX to display new HTML data, the .html() function

Here is the JavaScript I am using to handle an ajax request:

$(document).ready(function() {
  // Variable to hold original content
  var original_content_qty = '';
  $('.product-qty-<?php echo $products->fields['
    products_id ']; ?>').submit(function(e) {
    e.preventDefault();
    $.ajax({
      url: 'submit.php',
      type: 'POST',
      data: $(this).serialize(),
      dataType: 'html'
    }).done(function(data) {
      original_content_qty = $('.qty-update-<?php echo $products->fields['
                               products_id ']; ?>').html();
      console.log(original_content_qty);
      console.log(data);
      $('.qty-update-<?php echo $products->fields['
        products_id ']; ?>').fadeOut('slow', function() {
        $('.qty-update-<?php echo $products->fields['
          products_id ']; ?>').fadeIn('slow').html(data); //display a success message sent back via ajax
        $('.qty-update-<?php echo $products->fields['
          products_id ']; ?>').delay(1200).fadeOut('slow').html(data);
        $('.qty-update-<?php echo $products->fields['
          products_id ']; ?>').html(original_content_qty); // restore original content after success message
      });
    }).fail(function() {
      alert('Ajax Submit Failed ...');
    });
  });
});

Issue with restoring content:

When I try to restore the original content after displaying a success message, the content appears to display, fade out, then replace the original content. The success message displays correctly without trying to restore the content.

What's causing this behavior?

Console log for the data returned from ajax:

<style>.block .notice.invalid{display:none;}</style>
  <div class="alert alert-info">
  <strong>Stock updated</strong>
</div>

The data returned remains consistent regardless of attempting to restore content or not.

Console log for the original_content_qty shows:

Stock: <input type="hidden" name="products_id" value="289"><input type="text" name="products-quantity" value="0" size="4" class="product_quantity_input_289">

Could there be an error in how I'm trying to restore the content?

Answer №1

I put something together, you'll need to connect the steps into their own callbacks

$(document).ready(function() {
  // Variable to hold original content
  var original_content_qty = '';
  var form = $('.product-qty-42')
  form.submit(function(e) {
    e.preventDefault();
    $.ajax({
        url: 'submit.php',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'html'
      })
      .done(function(data) {
        var elem = $('.qty-update-42');
        var original_content_qty = elem.html();
        console.log(original_content_qty);
        console.log(data);
        elem.fadeOut('slow', function() {
          elem.html(data).fadeIn('slow', function() {
            elem.delay(1200).fadeOut('slow', function() {
              elem.html(original_content_qty).fadeIn('slow');
            });
          });
        });
      })
      .fail(function() {
        alert('Ajax Submit Failed ...');
      });
  });
});

$.mockjax({
  url: "submit.php",
  responseText: '<p>Worked</p>'
});
<form class="product-qty-42">
  <div class="qty-update-42">
    <input type="hidden" name="products_id" value="289"><input type="text" name="products-quantity" value="0" size="4" class="product_quantity_input_289">
  </div>
  <input type="submit" name="send">
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.6.2/jquery.mockjax.min.js"></script>

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

Learn how to seamlessly connect lists in Vue with these foolproof steps

<template> <div class="lists"> <div v-for="(list, key, i) in getAllBreeds" :key="i"> <div v-if="list.length"> <div v-for="(ele,i) in list" ...

Trouble with Angular: Passing output between child components is not working

Just dipping my toes into Angular, I started learning it yesterday for a take-home job interview project. Please excuse any rookie mistakes in advance. For some hands-on practice, I decided to work on a basic project where the main component (app) has two ...

What steps can be taken to delete a cookie when the server cannot be accessed?

Currently utilizing a node.js + express server and managing sessions for users who are logged in. I am curious about how a user can log out if the server becomes unreachable? In the usual method, I would simply call req.logout() on the request object in ...

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

Encountering a parsing issue: an unexpected token was found, expecting "," instead

I'm encountering a Parsing error that states: Unexpected token, expected ",". I've been unable to pinpoint where the missing "," is located. Please refer to the image below for the exact line of the error. const cartSlice = createSlice({ name ...

Displaying extra dropdown menus when a specific option is chosen within a pop-up using JQM

Currently, I have a popup that displays a dropdown list with options 1 to 4. Upon selecting an option from this dropdown, I would like to use an ajax call to show additional dropdown lists inside the popup window. I have created 4 divs for each of the sel ...

Finding the index of a chosen option in Angular

Attempting to retrieve the index of the selected option from a select element using Angular. The Angular (4) and Ionic 3 frameworks are being utilized. The template structure is as follows: <ion-select [(ngModel)]="obj.city"> <ion-option ...

It appears that the Next.js environment variables are not defined

Upon setting up a fresh next.js project using npx create-next-app@latest and configuring some environment variables in the .env.local file, I encountered an error when attempting to run the server. "Failed to load env from .env.local TypeError: Cannot ...

Searching for a point within a specified range using Sequelize

I have a model called Location with a field named coordinates of type geometry. I'm looking to create a function that takes in latitude, longitude, and radius as parameters, and returns all locations within that radius (in meters). I attempted to foll ...

tips for transferring a javascript function value to a label within a webform

Currently, I am in search of the latitude and longitude coordinates for a specific address input by the user. Upon clicking a button, the script provided below is triggered to display an alert with the latitude and longitude values: <script type="text/ ...

Using Alpine JS to rotate through images at regular intervals using the window.setInterval() method

Attempting to tackle a simple task using Alpine JS and the standard JS function setInterval. The goal is to create an image selector where images switch every second (1000ms). Here's what I have so far: <div x-data="imgFunc()"> ...

Why is it necessary to define a property outside the constructor in Typescript, when in Javascript I wouldn't have to do that?

When working with Javascript, creating a class like the one below allows us to avoid declaring and initializing a property named logs outside of the constructor: class Logger { constructor() { this.logs = []; } } However, transitioning to TypeScri ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

Developing an interactive website utilizing AngularJS, WCF Service, and SQL Server

Exploring the possibilities of creating a web application, I stumbled upon AngularJS. With plans to incorporate WCF Service and SQL Server into my project, I am intrigued by what these technologies can offer. I want to ensure that AngularJS aligns with my ...

Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value a ...

Replacing the tbody element in React with centered text using inline styles ---If you want

I am working with an empty array in React that I translate into state. When the array is empty, I want to insert a text that says "no match events yet..." into a react-bootstrap Table's tbody. In the current setup, I am struggling to center the text ...

Improve code efficiency by streamlining a function and using more effective syntax techniques

I've been learning how to condense code with jQuery. Can this script be written in a more concise manner without everything being on one long line? items.push('<li id="' + key + '">' + ' (key: ' + key + ')&apo ...

Employees are unable to operate within an HTML page embedded in a WPF project

When running scripts on an HTML page, the page tends to freeze until the script completes. This is why I am considering using workers. However, I have encountered a problem: <html> <head> </head> <body> <button onclick="startWor ...

Issue with AngularJS ngGrid rendering incorrect page size and malfunctioning pagination

I'm currently working on implementing ngGrid data pagination for some data retrieved from a service. The table displays correctly and the search filter is functional. However, despite setting the pageSize in my pagingOptions to 25, the table shows all ...

How come my form isn't functioning properly on mobile devices?

I recently downloaded a form from the website and integrated it within my desktop site successfully. However, when accessed on mobile devices, specifically iOS, the submit button changes to "sending ..." and the form gets stuck without displaying any erro ...