DEV Community

Cover image for handle Forms without PageRefresh
Frank Wisniewski
Frank Wisniewski

Posted on


handle Forms without PageRefresh

you only need a few lines of code

First, let's build the HTML file with a simple form...

<!DOCTYPE html>
<html lang=en>
  <meta charset=UTF-8>
  <link rel=stylesheet 
    <div class=container>
      <h2>Fetch Data</h2>
      <div class=grid>
        <input type=hidden 
            name=dbid value='10'>
        <label>First name
          <input type=text name=firstname 
            placeholder="first name"  required>
        <label>Last name
          <input type=text name=lastname 
            placeholder="last name" required>
      <label>Email address</label>
        <input type=email name=email 
          placeholder="email address" required>
        <small>We will send your e-mail address 
               to all mail order companies, banks 
               and insurance companies 😇</small>
  <script src="fetch.js"></script>
Enter fullscreen mode Exit fullscreen mode

screenshot from form:

form sample

now a few lines Vanilla JS...

  .addEventListener('submit', function (evt){
    let reqData = new FormData(this)
    reqData.append('action', 'update')
    fetch('fetch.php', { method: 'POST', body: reqData})
    .then (r => r.json())
    .then (data=>{
      if (data.status === "OK"){  
         // make your work
      if (data.status === "EMPTY"){  
         //make your work
      if (data.status === "HACKER"){  
        // call secret services
    }).catch(error => alert(error))
    return false;
Enter fullscreen mode Exit fullscreen mode

finally some PHP...

function jsonOut($myMessage){
    header('Content-Type: application/json');
    echo json_encode($myMessage);
function checkRequest($requestArray, $arrayKeys){
  foreach ($arrayKeys as $key){
    if (!isset($requestArray[$key])){
      JsonOut(['status' => 'HACKER',
      'message' => 'someone is trying to manipulate']);
    if ($requestArray[$key] == ''){
      JsonOut(['status' => 'EMPTY', 'field' => $key, 
      'message' => 'please fill in correctly']);
  return true;
$action = $_POST['action'] ?? "";    
if ($action === 'update'){
  $myRequestKeys = array('dbid', 'firstname', 'lastname', 'email');
  if(checkRequest($_POST, $myRequestKeys)) {
    //make your work...
    JsonOut(['status' => 'OK','message' => 'everything OK']);
Enter fullscreen mode Exit fullscreen mode


Top comments (1)

darkterminal profile image
Imam Ali Mustofa

It's funny when i read your post! But good job...

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await