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>
<head>
  <meta charset=UTF-8>
  <title>FetchData</title>
  <link rel=stylesheet 
   href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
  <form>
    <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>
        <label>Last name
          <input type=text name=lastname 
            placeholder="last name" required>
        </label>
      </div>
      <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>
      <button>Send</button>
    </div>
  </form>
  <script src="fetch.js"></script>
Enter fullscreen mode Exit fullscreen mode

screenshot from form:

form sample

now a few lines Vanilla JS...

document.querySelector('form')
  .addEventListener('submit', function (evt){
    evt.preventDefault()
    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
         console.log(data.message)
      }
      if (data.status === "EMPTY"){  
         //make your work
        console.log(data.message)
      }
      if (data.status === "HACKER"){  
        // call secret services
        console.log(data.message)
      } 
    }).catch(error => alert(error))
    return false;
})
Enter fullscreen mode Exit fullscreen mode

finally some PHP...

<?php
function jsonOut($myMessage){
    header('Content-Type: application/json');
    echo json_encode($myMessage);
    exit;
}
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

Done...

Top comments (1)

Collapse
 
darkterminal profile image
Imam Ali Mustofa

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