QuizCure
Find Available Solution Here!

jquery Refresh div

Deepak Nov 10, 2024

During website development, we might need to refresh particular div content with updated content for multiple scenarios such as

  • Show message or content from the server within div using jQuery ajax response
  • Showing validation message on form submit
  • Reload content of div after every n interval Display regular updates on specific page sections without reloading the page

We will learn here ways to reload div for different scenarios by jquery refresh div. Let's dive into example code for a better understanding:

jQuery ajax refresh div content on form submit

The following code demonstrates reloading div content using jQuery Ajax code by server response.

Let's understand with the following example form containing email text input and a submit button.

<div id="result"> </div>
<form method="post" id="demo" >
    <input type="text" name="email" id="email" class="form-control" placeholder="Enter your Email">
    <input type="submit" value="Submit" name="submitBtn" id="submitBtn" >
</form>
 

Here

<div id="result"> </div>
is blank div used with div Id result.

Now we don't want to reload the page after form submission. Therefore we can submit a form using Ajax to prevent page reload.

Please review the following code block to meet the objective: jQuery refresh div without reloading page.

<script  src="jquery-3.2.1.min.js"></script>

<script>
    $(document).ready(function () {
        $("form").submit(function (event) {
            $.ajax({
                url: './server.php', // sending ajax request to this server page
                type: 'post',
                dataType: "json",
                data: {
                   'email': $("#email").val()
                },
                success: function (response) {
                    $("#result").html(response.message);
                }
             });
         event.preventDefault();
        });
    });

</script>

Code Explanation:

  • Included jQuery library
  • The document-ready event is used here to ensure DOM is ready.
  • jQuery method submit is executed once the submit event is triggered.
  • jQuery Ajax method is used to perform asynchronous (non-blocking) HTTP requests to the server.
  • Url param is used to specify the request URL to the server. In our example it server.php
  • Type: request type whether Get/Post. We used a post request to the server.
  • dataType: Expected data type from the server. In our example, specified JSON means we are expecting a response in JSON format.
  • Data: represents data to be sent to the server. Data is appended in the URL in the GET request. In our example, we are sending email input to the server.
  • Success: method is invoked once we receive a successful response from the server.
  • Within the function block, we can handle further client-side manipulations. We are rendering server responses within the div with the id result.
  • event.preventDefault: as the name tells us, it prevents browsers from performing default behavior once the event is triggered.

Code on Server.php file

<?php

if (empty($_POST['email'])) {
    $data['success'] = false;
    $data['message'] = 'Email is required.';
} else {
    $data['success'] = true;
    $data['message'] = 'Received Email';
}

echo json_encode($data);
?>

Server.php Code detail:

Page on server requested by Ajax received data sent through Ajax and processed as per business logic. In our case above it received posted email values and checked for empty.

Return $data array in JSON format using json_encode as requested dataType from the client.

Therefore the following code

$("#result").html(response.message);

Will replace the content of div with message return from the server based on email value.

The above example is explained here just to give an overview of how we can reload div content using Ajax.

There are other ways to make Ajax post requests using the following method which depends on the jQuery version we used. Such as
$.post( "path_of_server_file", function( data ) {
  $( "#result" ).html( data );
});
 

For more detail about ajax you may visit here.

jquery refresh div on click event

In the previous example, we learned to update div content using server response via Ajax call.

It was a form submit event trigger. Here we will see a change of div content using the click event.

<script  src="jquery-3.2.1.min.js"></script>

<script>
    $(document).ready(function () {
        
         $( '#abc' ).on( 'click', function() { 
             $('#result').html( 'Link#abc is Clicked!' ); 
      }); 
    });

</script>
<div id="result"> </div>
<a href="javascript:void(0)" id="abc" >Click Me</a>
 

Code Explanation:

  • jQuery on the method used to attach the click event handler.
  • $( '#abc' ) is a selector attached with a click event. Therefore attached event will be executed Once the element with id #abc is clicked.
  • It will update div (with id as result) inner HTML content as Link#abc is Clicked! after clicking on the Click Me link.

jquery reload div after every N seconds

Scheduling div content to refresh its content can be done by using the setInterval method. setInterval function helps to execute a specified function or piece of code at given intervals. Here the interval is in milliseconds. Let's explore the following code block to learn jQuery auto-refresh div on specified time intervals.

Let's take a look into the below code to refresh div after every 5 seconds

<script  src="jquery-3.2.1.min.js?t=27"></script>

<script>
    $(document).ready(function () {

      function refresh() {
            $('#result').html(new Date($.now()));
        }

        setInterval(function () {
            refresh()
        }, 5000); //5 seconds
    });

</script>

<div id="result"> </div>
 

Explanation:

  • Executing piece of code to display current date-time within div.
  • The refresh function is called after every 5 seconds (5000 milliseconds)
  • Will display DateTime like Fri Jan 21 2022 20:29:02 GMT+0700 (Indochina Time) based on system timezone.

You may execute the above code and check the time changing within the div after 5 seconds.

Now, what if we need to stop this repeated process? :)

To stop this regular interval execution we need to use the function clearInterval.

But, We need to make sure to receive the return value (timer identifier) from the setInterval function that will be used to pass to clearInterval to stop further execution. Let's understand with the following code.

<script>
    $(document).ready(function () {

        function refresh() {
            $('#result').html(new Date($.now()));
        }

        var returnId = setInterval(function () {
            refresh()
        }, 5000); //5 seconds


        $("#stop").click(function () {
            stopExecution();
            $("#stop").html("Timer Stopped");
        });

        function stopExecution() {
            clearInterval(returnId);
        }

    });


</script>

<div id="result"> </div>


<a href="javascript:void(0)" id="stop">Stop Me</a>

Explanation:

  • The refresh function here defines show DateTime within the div once called.
  • returnId variable is defined to store the return value from the setInterval function.
  • stopExecution function is used to call the clearInterval method to stop further setInterval execution.
  • Click event-triggered once we click on the link with id as a stop. It calls stopExecution() on click and performs a clearing interval using the clearInterval function.

Was this post helpful?

Send Feedback

Practice Multiple-Choice Questions

  • ?
    Here is how div is defined:
    <div id="result">Hello</div>
    
    How to replace a div's inner HTML using its ID. Pick the right one?
    Options are:

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up