Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website,

I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information,

However, sometimes the page blinks before reloading, while other times it does not.

Since I'm working on a shopping cart page, I am using setTimeout to handle this functionality,

It allows users to edit their shopping cart items.

My plan is: once the user stops clicking the plus or minus buttons or typing for about 1 second,

ajax will be triggered to read the API, and after success, the page will reload.

Is there any way to prevent the page from blinking?

Maybe I can add a loading gif to show on the page?

Here's a snippet of my code:

var timeout = null;
$('.num').on('keyup', function() {
    var newNum = $(this).val();
    var pid = $(this).attr("name");

    clearTimeout(timeout);
    timeout = setTimeout(function() {
        if(newNum <= 0){
            alert("At least 1 product!");
            $(this).val("1");
            $.ajax({
                type: "post",
                url: myAPI,
                async: false,
                data: {
                    pid: pid,
                    newNum: 1
                },
                dataType: "json",
                success:function(data){
                    window.location.reload(true);                
                },
            });
        }else {
            $.ajax({
                type: "post",
                url: myAPI,
                async: false,
                data: {
                    pid: pid,
                    newNum: newNum
                },
                dataType:"json",
                success:function(data){
                    window.location.reload(true);                    
                },
            });
        }
    }, 1000)
});

Answer №1

If you want to display a loader gif and then remove it once the document has finished loading, you can follow these steps:

<div class="loader-fix" style="position:fixed;height:100vh;width:100vw;background:#ffffff;">
    <img src="your.gif" />
</div>
<script>
    $(window).on('load', function (e) {

        $('.loader-fix').fadeOut('slow', function () {
            $(this).remove();
        });
    });

</script>

Answer №2

When is it beneficial to utilize ajax for reloading a page in order to display updated data?

success:function(data){
                    window.location.reload(true);                    
                } 

What is the purpose of the code snippet above..?

In this scenario, a simple form submission would have sufficed, yet ajax was utilized to fetch data without any further processing.

If your intention is to refresh the page, consider following Şahin Ersever's suggested solution.

For creating a dynamic site that retrieves data from the backend and updates the frontend seamlessly without requiring a full page reload, implement something similar to this example:

<html>
  <body>
    <h1> Dynamic load using AJAX </h1>
    <div class="dynamic_div"> 
      <div class="some_class">
        <!-- additional elements containing potential dynamic or server-side-based data -->
         <!-- For instance: -->
         <h1> Name:- <?php echo $name;?> </h1>
         <p> <?php echo $some_other_variable;?> </p>
         <p> <?php echo $some_other_variable;?> </p>
         ....
        </div>
    </div>
    <button onclick="letsload()">Load</button>
    <script>
      function letsload(){
         $.post("someurl",{ data1: "value1", data2 : "value2"},
            function(data, status){
              if(status == "success"){
                 $('.dynamic_div').html(data);//Loading updated data
             }
         });
      }
    </script>
  </body>
</html>

You can output desired html/json or success/error codes on the data variable, then handle them accordingly within the ajax function.

Edit :-

In response to your comment stating

But I check...reload page, it can work
.

A quick fix involves maintaining the desired element inside a separate file, such as updated.php.

<div class="some_class">
<!-- additional elements containing potential dynamic data or server-side details-->

<!-- Like so -->

<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>

Upon successful ajax execution, load this div into the .dynamic_div container like this.

success:function(data){
                    $('.dynamic_div').load("updated.php");//Load the inside elements into div                
                }

This facilitates displaying updated data without refreshing the entire webpage, as changes were already implemented on the backend and loaded dynamically through load().

Feel free to leave a comment for any inquiries.

Answer №3

  • Utilize AJAX to retrieve data from a web server after the page has been fully loaded
  • Refresh a web page without having to reload it entirely
  • Efficiently send data to a web server in the background

Discover more about Ajax here

If you do not wish to reload the entire page, refrain from making an ajax call, but if you intend to fetch and display data through ajax, make use of JavaScript to update your HTML within the success message.

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

Unable to retrieve login information from the mysql database

I'm having trouble retrieving the admin credentials. I've reviewed the script multiple times but am unable to pinpoint the issue. Perhaps your expert eyes can identify something. loginshed.php <?php include('../settings/config. ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

How can I transfer a value from one form to another using AngularJS?

Trying to retrieve the Id from a table and pass it to a controller, however, I am facing an issue where the Id value is lost every time the form changes. Is there a better way to handle this? Below is the service and controller code: //Retrieving IdValue ...

Is it possible for a MySQL loop to only delete the first entry?

My MySQL looping is not working properly when I click the second button to get their id and continue with the rest of the process. Why is this happening? $(document).ready(function() { $("#deleteSchedule").click(function (e) { e.preventDefault(); ...

The Flux Router in React Native

I am diving into the world of React Native and currently working on creating a practice app. The issue I'm facing is with the routing functionality in my project. At the moment, I have three main components: the app itself, the router component, and o ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...

Revamp the HTML page by automatically refreshing labels upon every Get request

My HTML webpage requires real-time updates for one or more labels. To achieve this, I have incorporated CSS and JS animations into the design. Currently, I am utilizing Flask to handle all the calls. I face a challenge where I need to consistently update ...

The callback functions, such as afterMove, are not being executed

This code snippet is copied from Owl Carousel's official website. I am having trouble getting the callback functions like afterMove to work. Can anyone help me figure out why the afterMove function is not being called? It seems that none of the callba ...

Update the div and table without waiting for a specific time interval when an event happens

Currently, I have a table within a div that includes both editing and deleting functionality for records. After deleting a record, I want the table to be automatically updated with fresh data without having to reload the page. Can someone please provide me ...

Waiting for an Element to Become Visible in Selenium-Webdriver Using Javascript

When using selenium-webdriver (api docs here), how can you ensure that an element is visible before proceeding? Within a set of custom testing helpers, there are two functions provided. The first function successfully waits for an element to exist, howeve ...

A PHP guide on iterating through statement results to populate an associative array

I am struggling to find the correct syntax to iterate through my results and populate them into an associative array. Currently, it only retrieves the first result and does not continue looping through the rest of the data. I have attempted various combina ...

The synopsis cannot be displayed by the RottenTomatoes API

I'm having some trouble with the RottenTomatoes movies API. I've been trying to display the movie's synopsis below the input field, but it's not working as expected. Can anyone point out what might be causing the issue here? If you nee ...

Autonomous JQuery Modules

Is it possible to separate the functions in JQuery and use only the ones needed by splitting the file with PHP? By doing this, I aim to improve page speed, save bandwidth, and have more control over the functions used through the backend. Can the functio ...

Having trouble with accessing controls within an UpdatePanel?

I am attempting to access Page Controls at Page_Load, execute a database query, and modify the visibility of controls. Here is the Code: foreach (Control thiscontrol in ContentPlaceHolderBody.Controls) { try { if (thiscontrol.ID.Contains("Tex ...

"Efficiently fetching and handling multiple rows with

Having 2 questions: 1. Retrieving Ajax data from query.php like this: echo json_encode($records, JSON_UNESCAPED_UNICODE); This results in: [{"cinfo_id":"25","fullName":"علی علوی","phone":"123456","mail":"<a href="/cdn-cgi/l/email-protection" ...

The button works properly in JSFiddle, however, it is not able to clear the ordered list in the

DEMO Creating a script that captures mouse click coordinates and appends them to a list. The functionality works, except for an issue with the clear button not working properly. After making corrections in jsfiddle, the script functions correctly. Howeve ...