Display AJAX Status and Message Boxes with JavaScript

Show request state without blocking the page

A status element can show when a request starts, when the server finishes, and whether an error occurred. The demo posts the form to msgck.php, reads JSON, and uses textContent for server-provided text.

const response = await fetch('msgck.php', {
  method: 'POST',
  body: new FormData(form)
});
const payload = await response.json();
document.getElementById('msg').textContent = payload.data[0].msg;
While working in Ajax scripts we have to send data to server and then receive the response from the server. During this process the visitor has to wait for the next course of action. We must communicate to our visitor about the process going on and ask them to wait. Now there are three stages.

We must hide the message are once the page load.
Display the message asking to wait once the data is submitted.
Display the result message as returned by Server.


We will be extensible using layers by using Div tags to control the display and managing the content . Before going to these steps let us understand some common display properties frequently used.

One common way to display a Div tag


<div id=msg style="position:absolute; width:300px; height:25px; 
     z-index:1; left: 400px; top: 0px; 
     background-color: #c1c1c1;      border: 1px none #000000">This is message area
</div>

To change the content of the Div tag


document.getElementById("msg").textContent="Job Completed ...";

To change the background color of the image Tag


document.getElementById("msg").style.background='#f1f1f1';

Border color

For more border style options read CSS
document.getElementById("msg").style.borderColor='red';

// red = #f00000; green = #00f040; yellow = #f0f000; brick= #f0c000; light yellow = #f0f0c0

To display ( visible ) the Div tag layer


document.getElementById("msg").style.display='inline';

To Hide ( make it Invisible ) the Div Tag


document.getElementById("msg").style.display='none';

To Hide after some time interval

We may require to hide the message displayed after some time. For this we will use JavaScript setTimeout function.
setTimeout(() => { document.getElementById('f1').style.display = 'none'; }, 2000);
The callback form of setTimeout() avoids evaluating a string as JavaScript.

Visit the demo link below. We have kept a delay of 5 seconds at the server side to display the messages properly.
Demo Message Box
The demo uses msg.php for the browser interface, msg.htm as a standalone source example, and msgck.php as the JSON processor.
<script>
const form = document.getElementById('myForm');

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const status = document.getElementById('f1');
  status.textContent = 'Data posted to server ...';

  try {
    const response = await fetch('msgck.php', {
      method: 'POST',
      body: new FormData(form)
    });
    const payload = await response.json();
    if (!response.ok) throw new Error(payload.error);

    document.getElementById('msg').textContent = payload.data[0].msg;
    document.getElementById('msg1').textContent = payload.data[0].msg1;
    status.textContent = 'Job Completed ...';
    setTimeout(() => { status.style.display = 'none'; }, 2000);
  } catch (error) {
    status.textContent = error.message || 'Unable to complete the request.';
  }
});
</script>
Here is the code for msgck.php page
<?php
header('Content-Type: application/json; charset=UTF-8');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'POST method required']);
    exit;
}

$userid = trim((string)($_POST['userid'] ?? ''));
$password = (string)($_POST['pw'] ?? '');

if ($userid === '' || $password === '') {
    http_response_code(400);
    echo json_encode(['error' => 'User ID and password are required']);
    exit;
}

sleep(5);
echo json_encode([
    'data' => [[
        'msg' => 'Data Received',
        'msg1' => 'Data Processing done',
    ]],
]);
?>

Ajax Json XML


Subscribe to our YouTube Channel here



plus2net.com







Mohit Aray

29-10-2014

sir i need ur help m developing fee management system and i want to display a notification for those students whose fee is due or whose allow time is complited can u help me
karthik

15-09-2015

sir i need ur help m developing fee management system and i want to display a notification for those students whose fee is due or whose allow time is complited can u help me
smo1234

15-09-2015

Do you have skill of developing scripts using PHP & MySQL ?




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer