JEFFRY A. DECOLA

MY FRONTEND AND BACKEND API EXAMPLES

GITHUB REPO

SEND DATA FROM A BROWSER TO A WEB SERVER

Using an Ajax XMLHttpRequest (XHR) POST Call

Code written in javascript and php

send-data-from-browser-to-web-server-using-ajax-xhr-post-call

TRY IT

Two numbers will be sent from a browser (client) to a web server (server) that will calculate and return the sum.

I used my dynamic_items_container php container for the layout

OPERAND 1

+
OPERAND 2

=
SUM
ADD
RESET

XMLHttpRequest (XHR) POST Call

JAVASCRIPT HIGHLIGHTS (CLIENT SIDE)


        // PHP FILE LOCATION
        var url = 'path to file/filename.php';

        // CREATE A NEW REQUEST
        postRequest = new XMLHttpRequest();
        
        // CONVERT JSON TO STRING
        var attributesJSONString = JSON.stringify({
            "operand1": operand1,
            "operand2": operand2
        });

        // OPEN CONNECTION - CREATE POST REQUEST
        postRequest.open  'POST' , url, true);

        // SEND JSON FORMAT
        postRequest.setRequestHeader('Content-Type', 'application/json');
        postRequest.send(attributesJSONString);

        // LISTEN AND KICK OFF FUNCTION WHEN READY
        postRequest.onreadystatechange = function() {
            ...see code...
        }

        

PHP HIGHLIGHTS (SERVER SIDE)


        // GET THE JSON DATA FROM THE USER
        header("Content-Type: application/json");
        $attributesJSON = json_decode(file_get_contents("php://input"));

        // UN PARSE IT
        $operand1 = $attributesJSON->operand1;
        $operand2 = $attributesJSON->operand2;

        // DO SOMETHING
        ...