Javascript Fetch API to send data

Jun 12 · 3 min read

In general, we use Javascript to send requests to retrieve data from the web server without the need to reload the page.

Previously, people are used to exchange data by the XMLHttpRequest object (XHR). However, it’s a bit messy to organize the code since it requires you to define object and call back your response separately.

At present, Javascript Fetch API is popular for useful data retrival.

Send data

You are allowed to create a fetch object with method either “GET” or “POST”. In addition, you can add headers within your function.

// GET
// POST (More often to use): retrieve data by posting data to the web server, usually when login to the web serverconst data = { username:"REPLACE_BY_YOUR_USERNAME", password:"REPLACE_BY_YOUR_PASSWORD"}; // form your data in JSON formatfetch('PATH_TO_URL',{
headers: { 'content-type': 'application/json' }
}// you can replace headers with {'Accept': 'application/json'} to require the format of return data. Besides, you can customize other requirements in headers, such as cookies.

Listen for a Response

when expecting a response from the web server, Javascript’s Fetch API is user-friendly enough.

THEN allows you to get data, and you can deal with data after ARROW. Usually, if you are not sure about the return from server, you are highly recommended to use console to debug your code. Additionally, CATCH enables you to catch a error.

const data = {username:"YOUR_NAME",password:"YOUR_PWD"};
fetch("PATH_TO_URL", {
method: "POST",
body: JSON.stringify(data)
.then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:',error))

Example: Login as a User

we apply PHP + JS + MySQL on AWS EC2 Instance to realize login function on browser.

// MySQL on AWS EC2 Instance: create a table 
create table users (
username varchar(255) NOT NULL,
password varchar(255) NOT NULL,
joined timestamp NOT NULL DEFAULT current_timestamp,
primary key (username)
) engine = InnoDB default character set = utf8 collate = utf8_general_ci;

Note: pay attention to the length of password if you want to hash your password.

// HTML: login.html with built-in JS// Javascript
$("#login").click(function() {
showLogin(); // remember to create a link with id = login
function showLogin(){
var login_usrvalid = false;
var login_pwdvalid = false;
width: 350,
height: 310,
modal: true,
buttons: {
"Log in": function(){
close: function() {

if(checkLength($("#login-username"),"username", 3, 16)&&checkRegexp($("#login-username"),/^[0-9a-zA-Z]+$/,"Username may consist of a-zA-Z and 0-9.")){
if(checkLength($("#login-password"),"password", 3, 16)&&checkRegexp($("#login-password"),/^[0-9a-zA-Z]+$/,"Password may consist of a-zA-Z and 0-9.")){
// login-dialog is hide before clicking "login" link
<form id="login-dialog" class="dialog" title="Log in">
<p class="validateTips">All form fields are required.</p>
<input type="text" id="login-username" placeholder="Username" class="text ui-widget-content ui-corner-all"/>
<input type="password" id="login-password" placeholder="Password" class="text ui-widget-content ui-corner-all"/>
<input id="login_btn" type="submit" tabindex="-1" style="position:absolute; top:-200px">

Note: you can replace login-dialog by any kind of form. Also, you may want to replace your password validation function according to you own need.

// PHP: login_ajax.php
ini_set("session.cookie_httponly", True); // The following line sets the HttpOnly flag for session cookies - make sure to call it before you call session_start()
session_start();header("Content-Type: application/json"); // Since we are sending a JSON response here (not an HTML document), set the MIME Type to application/json
//Because you are posting the data via fetch(), php has to retrieve it elsewhere.
$json_str = file_get_contents('php://input');
//This will store the data into an associative array
$json_obj = json_decode($json_str, true);
//Variables can be accessed as such:
//Prevent Reflected XSS attacks
$username = htmlentities($json_obj['username']);
$password = htmlentities($json_obj['password']);
//This is equivalent to what you previously did with $_POST['username'] and $_POST['password']
$mysqli = new mysqli('localhost','hlan','lanhou199681','icalendar');
printf("Conncetion Failed:%s\n",$mysqli->connect_error);
$stmt = $mysqli->prepare("select password from users where username=?");
printf("Query Prep Failed: %s\n", $mysqli->error);
$stmt->bind_param('s', $username);
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
/* If there are results from database push to result array */
if ($num_of_rows > 0) {
while($row = $result->fetch_assoc()) {
$password_hash = $row['password'];
// validate password
if(password_verify($password, $password_hash)){
$_SESSION['username'] = $username;
$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
$login_status = true;
$login_status = false;
$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
/* send a JSON encded array to client */
echo json_encode(array(
"login_status" => $login_status,
"token" =>$_SESSION['token']

Note: this php file allows to connect to MySQL database and send data back to your html.