Search code examples
javascriptphphtmlrestapache

Receive data from client-side on server-side


I have an html page where clients insert a url so that it can be stored on a file on the server side.

The issue that I am having is that I cannot figure out how to receive client data on the server

Here is my html script

<!DOCTYPE html>
<html>
    <body>
        <input type="url" id="link"><br>
        <button onclick="myFunction()">Download</button>

        <script>
            function myFunction() {
                var url= document.getElementById("link").value
            }
            
        </script>
    </body>
</html>

How can I send the data of the "url" variable to my server?

I am using apache so it naturally supports php

Inside the function I tried to use fetch in combination with a php file

function myFunction() {
    var url= document.getElementById("link").value
    fetch(".php", {
    "method": "POST",
    "headers": {
    "Content-Type": "application/json; charset=utf-8"
                            },
    "body": JSON.stringify(url)
    }).then(function(response){
        return response.text();
    }).then(function(data){
        console.log(data);
    })
}

And the php file

<?php
    if(isset($_POST)){
        $data = file_get_contents("php://input");
        $link = json_decode($data);
        echo $link ;
    }

I was expecting to receive the url from the text input but instead the console.log returned the whole html script


Solution

  • In your script, just update the fetch(".php", { line. You need to give a file name here.

    For example, if the name of the PHP file which processes the data is server.php, you have to write fetch("server.php", {

    This should solve your issue.