How to do a POST request from a browser extension to localhost WITHOUT JQUERY?

  browser-extension, javascript, php, xmlhttprequest

This type of question has already been asked many times, but I can’t find an answer that:

  1. Does not use jQuery

  2. Works

jQuery answers: https://stackoverflow.com/a/44105591, https://stackoverflow.com/a/43393223

Not jQuery, but doesn’t work: https://stackoverflow.com/a/38982661

"Drop that and try jQuery"

First of all, I’m trying to do this with a browser extension.

Here is my (only) JS file:

// ...

function log(info,time){
    if(time===undefined)time=true;
    var xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange=function(){
        if(this.readyState===4&&this.status===200){
            console.log(this.responseText);
        }
    }
    info="http://localhost/log.php?log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
    xhttp.open("GET",info,true);
    xhttp.send(null);
}

// ...

Of course, this uses GET. info is a string, and time is either undefined (handled in the function) or boolean.

This is how I tried to use POST:

function log(info,time){
    if(time===undefined)time=true;
    var xhttp=new XMLHttpRequest();
    xhttp.onreadystatechange=function(){
        if(this.readyState===4&&this.status===200){
            console.log(this.responseText);
        }
    }
    info="log_item="+encodeURIComponent(info)+"&time="+(time?"true":"false");
    xhttp.open("POST","http://localhost/log.php",true);
    xhttp.send(JSON.stringify({
        "log_item":info,
        "time":time?"true":"false"
    }));
}

As taken from https://stackoverflow.com/a/38982661

And here is my log.php:

<?php
header("Access-Control-Allow-Origin: *");
if(isset($_POST["log_item"],$_POST["time"])){
    $_POST["log_item"]=urldecode($_POST["log_item"]);
    if($_POST["time"]==="true")file_put_contents("log.html","<li><b>[".date('l, F j, Y at h:i:s A')."]: </b>$_POST[log_item]</li>n",FILE_APPEND);
    else file_put_contents("log.html",$_POST["log_item"]."n",FILE_APPEND);
    echo $_POST["time"];
}

You shouldn’t have to worry about it, though. It just logs to log.html.

I can’t find a working solution to this (or maybe I’m not using the working solutions correctly). And again your answer should not include jQuery.

Source: Ask PHP

LEAVE A COMMENT